In my project I am trying to use doughnut chart as a separate component. I am passing some values from a component to the doughnut chart component. It is not showing the correct chart. I am passing the values from other component to the chart component as follows:
<DoughnutChart wrong={wrong} right={right} />
In the doughnutchart component the values are showing in the props but chart is not working.
import { useEffect, useRef, useState } from 'react';
import Chart from 'chart.js/auto';
const DoughnutChart = (props) => {
const chartRef = useRef(null);
const curwrong = props.wrong;
const curright = props.right;
const chartdata = {
labels: ['Wrong', 'Right'],
datasets: [{
data: [curwrong,curright],
backgroundColor: ['rgb(197, 0, 0)', 'rgb(0, 223, 0)']
}]
};
// Options for the chart
const options = {
plugins: {
title: {
display: true,
text: 'Exam Result'
}
}
};
useEffect(() => {
const data = chartdata;
// Create the chart instance
const myChart = new Chart(chartRef.current, {
type: 'doughnut',
data: data,
options: options
});
// Clean up function to destroy the chart when component unmounts
return () => myChart.destroy();
}, []);
return (
<div style={{width:300}}>
<canvas ref={chartRef}></canvas>
</div>
);
};
export default DoughnutChart;