PiChart.js 2.13 KB
import React, { memo } from "react";
import { Pie, PieChart, Sector, ResponsiveContainer } from 'recharts';

const renderActiveShape = (props) => {

    const RADIAN = Math.PI / 180;
    const { cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle, fill, payload, percent, value, name, color, font_color } = props;
    const sin = Math.sin(-RADIAN * midAngle);
    const cos = Math.cos(-RADIAN * midAngle);
    const sx = cx + (outerRadius + 10) * cos;
    const sy = cy + (outerRadius + 10) * sin;
    const mx = cx + (outerRadius + 30) * cos;
    const my = cy + (outerRadius + 30) * sin;
    const ex = mx + (cos >= 0 ? 1 : -1) * 22;
    const ey = my;
    const textAnchor = cos >= 0 ? 'start' : 'end';

    return (
        <g>
        <Sector
            cx={cx}
            cy={cy}
            innerRadius={innerRadius}
            outerRadius={outerRadius}
            startAngle={startAngle}
            endAngle={endAngle}
            fill={color}
        />
        <Sector
            cx={cx}
            cy={cy}
            startAngle={startAngle}
            endAngle={endAngle}
            innerRadius={outerRadius + 6}
            outerRadius={outerRadius + 10}
            fill={color}
        />
        <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={color} fill="none" />
        <circle cx={ex} cy={ey} r={2} fill={color} stroke="none" />
        <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} style={{fontWeight:'bold'}} textAnchor={textAnchor} fill={font_color}>{`${name}`}</text>
        <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} dy={18} textAnchor={textAnchor} fill={font_color}>
            {`${(value)}%`}
        </text>
        </g>
    );
};

const PiChart = ({ data, color }) => {
    return (
    <>
        <ResponsiveContainer width={'100%'} height={300}><PieChart>
            <Pie 
                activeIndex={Array.from({length: data.length}, (_, i) => (i-1) + 1)}
                activeShape={renderActiveShape}
            data={ data } dataKey="value" cx="50%" cy="50%" innerRadius={70} outerRadius={100} fill="#82ca9d" />
        </PieChart></ResponsiveContainer>
    </>
    )
}

export default memo(PiChart);