react-pie-chart-easy
Version:
A simple and customizable React pie chart component. React pie chart component which is very easy to use and have multiple configuration options for more customization.
86 lines (79 loc) • 1.95 kB
JavaScript
import React from "react";
import { Pie } from "react-chartjs-2";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
ChartJS.register(ArcElement, Tooltip, Legend);
const ReactPieChart = ({
data,
backgroundColor = [],
borderColor = [],
radius = 100, // Controls the size of the pie chart % of the canvas
animate = "no",
zoom = false,
rotate = 0,
showLegend = true,
cutout = 0, // Added cutout prop to control the donut hole size
}) => {
const chartData = {
labels: data.map((item) => item.title),
datasets: [
{
data: data.map((item) => item.value),
backgroundColor:
backgroundColor.length > 0
? backgroundColor
: data.map((item) => item.color),
borderColor:
borderColor.length > 0 ? borderColor : data.map((item) => "white"),
borderWidth: 1,
},
],
};
const options = {
responsive: true,
plugins: {
tooltip: {
callbacks: {
label: function (tooltipItem) {
return data[tooltipItem.dataIndex].tooltip || tooltipItem.raw;
},
},
},
legend: {
display: showLegend,
},
},
animation:
animate === "yes"
? {
animateScale: true,
animateRotate: true,
}
: false,
elements: {
arc: {
borderWidth: 2,
radius: radius,
},
},
rotation: rotate,
cutout: cutout,
};
if (zoom) {
options.plugins.zoom = {
pan: {
enabled: true,
mode: "xy",
},
zoom: {
enabled: true,
mode: "xy",
},
};
}
return (
<div style={{ width: "100%", height: "100%", position: "relative" }}>
<Pie data={chartData} options={options} />
</div>
);
};
export default ReactPieChart;