How to reach Chart.helpers.color in a React context with chart.js 3.0.0?

4.7k Views Asked by At

I've managed to figure out how to import and register models for the new chart.js 3.0.0 in a React app, but I'm at a loss as to how to get Chart.helpers.color to be used. Here are my imports and register:

import React from 'react';
import { Chart, Tooltip, CategoryScale, LinearScale, Title } from 'chart.js';
import { Matrix, MatrixController } from 'chartjs-chart-matrix';

Chart.register(Tooltip, CategoryScale, LinearScale, Title, Matrix, MatrixController);

And yet, when I call Chart.helpers.color, as below:

        datasets: [{
            label: 'My Matrix',
            data: chartData,
            backgroundColor(context) {
                const value = context.dataset.data[context.dataIndex].v;
                const alpha = Math.log10(value) / 4;
                    return Chart.helpers.color('green').alpha(alpha).rgbString();
            },
            ...

the app throws TypeError: chart_js__WEBPACK_IMPORTED_MODULE_1__.Chart.helpers is undefined

Anyone know how I can get this React app to reach Chart.helpers? Thanks! (Or, of course, an alternative would be welcome! This is for plotting a heat map using alpha to represent value.)

1

There are 1 best solutions below

2
On

I figured this out, and I'm going to post up the answer because this has taken me days to figure out. I found a blurb on the chart.js repo about it here:

https://github.com/chartjs/Chart.js/blob/master/docs/docs/developers/publishing.md

So in my example I have at the top:

import React from 'react';
import { Chart, Tooltip, CategoryScale, LinearScale, Title } from 'chart.js';
import { color } from 'chart.js/helpers';
import { Matrix, MatrixController } from 'chartjs-chart-matrix';
Chart.register(Tooltip, CategoryScale, LinearScale, Title, Matrix, MatrixController);

and then I access Chart.helpers.color this way:

return color('green').alpha(alpha).rgbString();