Skip to content

Why doesn't the chart use new plugins?

Chart.js takes the plugins of a chart when it creates the chart, so react-chartjs-2 passes the plugins prop only then. A new plugins array does not change a chart that already exists.

Values that a plugin uses can change through its options: put them in options.plugins under the id of the plugin, and the plugin gets them as the third argument of its hooks. Options are updated without recreating the chart:

const centerText = {
id: 'centerText',
afterDraw(chart, args, options) {
const { ctx, chartArea } = chart
ctx.save()
ctx.textAlign = 'center'
ctx.fillText(
options.text,
(chartArea.left + chartArea.right) / 2,
(chartArea.top + chartArea.bottom) / 2
)
ctx.restore()
}
}
function Votes({ total }) {
return (
<Doughnut
data={data}
plugins={[centerText]}
options={{ plugins: { centerText: { text: `${total} votes` } } }}
/>
)
}

To turn plugins on or off, give the chart a key that changes with them. React then mounts a new chart, and Chart.js creates it with the new plugins:

<Bar
key={showLabels ? 'labels' : 'plain'}
data={data}
plugins={showLabels ? [ChartDataLabels] : []}
/>

The redraw prop recreates the chart as well, but every time data or options change, not only when the plugins do.