The error:
Failed to compile ./app/Components/Barchart.jsx ReactServerComponentsError: You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server components by default. 1 | import React, { useState, useEffect } from 'react'; : ^^^^^^^^^ 2 | import { Bar } from 'react-chartjs-2'; 3 | import { 4 | Chart as ChartJS, `---- Maybe one of these should be marked as a client entry with "use client": ./app/Components/Barchart.jsx ./app/page.js This error occurred during the build process and can only be dismissed by fixing the error.
Why is it appearing when I'm trying to develop like this:
import React, { useState, useEffect } from 'react';
import { Bar } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
const BarChart = () => {
const [chartData, setChartData] = useState({
datasets: [],
});
const [chartOptions, setChartOptions] = useState({});
useEffect(() => {
setChartData({
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: 'Sales $',
data: [18127, 22201, 19490, 17938, 24182, 17842, 22475],
borderColor: 'rgb(53, 162, 235)',
backgroundColor: 'rgb(53, 162, 235, 0.4',
},
]
})
setChartOptions({
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Daily Revenue'
}
},
maintainAspectRatio: false,
responsive: true
})
}, [])
return (
<>
<div className='w-full md:col-span-2 relative lg:h-[70vh] h-[50vh] m-auto p-4 border rounded-lg bg-white'>
<Bar data={chartData} options={chartOptions} />
</div>
</>
);
};
export default BarChart;
I am using chartjs to make a bar chart in my next app but I am getting an error in the browser. So how do I prevent it and what is the reason for that. I am using the latest Nextjs version and and I got the chart dependencies from this link https://react-chartjs-2.js.org/