Search code examples
typescriptreact-hooksreact-typescript

Rechart PieChart- How to convert to typescript?


I want to use a function like this rechart demo https://codesandbox.io/s/pie-chart-with-customized-active-shape-y93si?file=/src/App.tsx

it's too long to show so I'm bringing here my demo to explain:

export const PieChartTab =()={
    const renderActiveShape = (props:any ) => 
    {
        const { cx, cy, payload, fill } = props;

        return (
            <g>
                <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>
                    {payload.name}
                </text>
            </g>
        )
    }

 return (
        <div>
            <PieChart width={230} height={230}>
                <Pie
                    activeShape={renderActiveShape}
                    data={dataAmHours}
                    cx={100}
                    cy={100}
                    blendStroke
                </Pie>
            </PieChart>
        </div>
    );
})

I want to use it in react typescript, but I don't know how to declare and get the props in the right way.


Solution

  • Ok, I got it.

    First, I had to add the 'activeIndex' prop to the Pie component. Then I declared the props.

    export const PieChartTab =()={
        const renderActiveShape = (props: { cx: number, cy: number, fill: string}) => 
        {
            const { cx, cy, fill } = props;
    
            return (
                <g>
                    <text x={cx} y={cy}  textAnchor="middle" fill={fill}>
                        {"data I want to show"}
                    </text>
                </g>
            )
        }
    
     return (
            <div>
                <PieChart width={230} height={230}>
                    <Pie
                        activeIndex={8}
                        activeShape={renderActiveShape}
                        data={dataAmHours}
                        cx={100}
                        cy={100}
                        fill={'#FFD669'}
                        blendStroke
                    </Pie>
                </PieChart>
            </div>
        );
    })
    

    Note that the props I want to get for the renderActiveShape function I had to define first in the Pie component props.