-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpie.tsx
More file actions
73 lines (66 loc) · 1.85 KB
/
pie.tsx
File metadata and controls
73 lines (66 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import React, { useEffect, useRef } from "react";
import Chart from "chart.js/auto";
import useWindowSize from "../../hooks/useWindow";
const generateRandomColor = () => {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
const PieChart = ({ data }) => {
const chartRef = useRef(null);
const { height } = useWindowSize();
useEffect(() => {
// Generate dynamic background colors for each segment based on labels
const dynamicColors = data.labels.map(() => generateRandomColor());
// Create a new pie chart instance
const ctx = chartRef.current.getContext("2d");
const chart = new Chart(ctx, {
type: "pie",
data: {
labels: data.labels,
datasets: [
{
data: data.datasets[0].data,
backgroundColor: dynamicColors,
},
],
},
options: {
responsive: true,
plugins: {
tooltip: {
callbacks: {
label: (context) => {
const label = data.labels[context.dataIndex];
const value = data.datasets[0].data[context.dataIndex];
const total = data.datasets[0].data.reduce((acc, curr) => acc + curr);
const percentage = ((value / total) * 100).toFixed(2);
return `${label}: ${value} (${percentage}%)`;
},
},
},
},
},
});
// Clean up the chart instance on component unmount
return () => {
chart.destroy();
};
}, [data]);
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
maxHeight: `${height - 100}px`,
}}
>
<canvas ref={chartRef} />
</div>
);
};
export default PieChart;