1

I am using Chart.js 3.x.x with Next.js like so:

import { useRef, useState } from 'react';
import 'chart.js/auto';
import { defaults } from 'chart.js';
import { Bar, Doughnut } from 'react-chartjs-2';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { barOptsObj, doughnutOptsObj } from 'lib/chartjs-options';

const Graph = (props) => {
  const [chartType, setChartType] = useState({
    id: 'c1',
    name: 'Pie Chart',
    value: 'pie',
  });
  const chartRef = useRef(null);
  const chart = chartRef.current;

  // a click handler for my custom legend
  const legendClickHandler = (index) => {
    console.log(chart); // the log that presents the chart object on every legend click
    const { type } = chart.config;
    if (type === 'pie' || type === 'doughnut') {
      chart.toggleDataVisibility(index);
      chart.update();
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.chart}>
        {chartType.value === 'pie' && (
          <>
            <Doughnut
              data={chartDataObj}
              options={doughnutOptsObj}
              plugins={[ChartDataLabels]}
              ref={chartRef}
            />
          </>
        )}
        {chartType.value === 'bar' && (
          <Bar
            data={chartDataObj}
            options={barOptsObj}
            plugins={[ChartDataLabels]}
            ref={chartRef}
          />
        )}
      </div>
    </div>
  );
};

export default Graph;

Now I am using the chart object in an onClick function I've built for my custom legend. On first render everything works as expected, but after using a dropdown to switch to a bar chart and back, it renders fine but the object now has ctx and canvas properties as null. It means the function is useless if the user switched chart type and back.

console log

Why does it happen? How can I avoid it?

XanderTEM
  • 81
  • 10
  • This should be because the `destroy()` method is called (maybe during cleanup by react-chartjs-2). Hence you will need to instantiate the Chart.js again. – Levi Chimezie Dec 27 '22 at 11:20

0 Answers0