so I am trying to add graphs using ChartJS for my NextJS application. However, I seem to have issues rendering it. I also followed other tutorials and/or articles but it seems that I get the same error.
The error I get is this:
Server Error
TypeError: Cannot read properties of null (reading 'useRef')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
I am not sure why I am getting that error since I am not using useRef
hook in my code.
Here is my code for root/pages/admin/home.js
import Head from 'next/head'
import Image from 'next/image'
import LineGraph from '../../components/admin/line'
export default function Home() {
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<LineGraph />
</main>
</div>
)
}
Here is my code for the LineGraph root/components/admin/line.js
import React, { useRef } from 'react';
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js/auto';
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
fill: false,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const LineGraph = () => {
return (
<canvas>
<h2>Line Example</h2>
<Line
id="lineChart"
data={data}
width={400}
height={400}
/>
</canvas>
);
}
export default LineGraph;
PS: If this question is duplicated, pls drop the link and I'll give it a go. Thank you very much for your help guys.
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"
},