Chartjs-ChartJS in NextJS throws error TypeError: Cannot read properties of null (reading 'useRef')

1๐Ÿ‘

โœ…

So, I figured it out. It has something to do with the package version. Inside my package.json file, I have the following dependencies:

"dependencies": {
        "next": "12.3.1",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "chart.js": "^2.9.3",
        "react-chartjs-2": "^2.9.0"
}

To make it work, I had to manually install chart.js and react-chartjs-2 with a specific version. So, my graph finally works and my package.json looks like this:

"dependencies": {
    "chart.js": "^3.9.1",
    "next": "12.3.1",
    "react": "18.2.0",
    "react-chartjs-2": "^4.3.1",
    "react-dom": "18.2.0"
  },

0๐Ÿ‘

First since you are not using the useRef you can remove the import.

Your code likely fails on that you put your HTML inside of a canvas element which is not something you should do.

React-chartjs automatically will create the canvas tag for you. So you should change your canvas tag to be a div or even cleaner a fragment

const LineGraph = () => {
  return (
    <>
      <h2>Line Example</h2>
      <Line
        id="lineChart"
        data={data}
        width={400}
        height={400}
      />
    </>
  );
}

Leave a comment