Suriya Rakhunathan
Suriya Rakhunathan

Reputation: 149

Click Event not working on Recharts Pie Label

I am working on Recharts plugin for a React Project to display a Piechart with 2 sections and customized label.

My requirement is to get the value of the pie section on click. I am able to achieve it through adding onClick props to Pie tag. But the issue is when i click on the label in the PieCharts, the click event is not triggered.

Some search results say, we cant have click event on svg child elements like rect, circle, text, etc.

Anyone have faced such issues? Please help me how to proceed on this.

Pie Chart Code

const data = [{ name: 'On Time', value: Number(70), mode: 'total' }, 
              { name: 'Delayed', value: Number(30), mode: 'total' }];
const COLORS = ['#008000', '#fa833c'];
<PieChart width={300} height={300} className={'mainPie'}>
    <Pie dataKey="value"
         activeIndex={this.state.activeIndex}
         labelLine={false}
         label={renderCustomizedLabel}
         data={data}
         cx={150}
         cy={130}
         outerRadius={120}
         innerRadius={60}
         onClick={this.onPieClick}
         fill="#8884d8">
         {data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)}
     </Pie>
 </PieChart>

On Click Event Function

onPieClick = (index, data) => {
    console.log('onPieClick'+index.value);
}

Custom Label Codebase

const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index, mode}) => {
let radius = innerRadius + (outerRadius - innerRadius) * 0.3;
let x = cx + radius * Math.cos(-midAngle * (Math.PI / 180));    
let y = cy + radius * Math.sin(-midAngle * (Math.PI / 180));
return (
(<g>
        <text x={cx} y={cy} dy={8} textAnchor="middle" fill="black" fontSize="12">DELIVERIES</text>
        <text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} fontSize="12" dominantBaseline="central">
            {(percent * 100).toFixed(2)}%
        </text>
    </g>
);

}

Below is the screenshot of the chart.

Pie Chart

Upvotes: 2

Views: 4828

Answers (1)

Alex
Alex

Reputation: 921

I had this issue with Rechart Bar Chart too. I solved it by setting pointerEvents of the custom label to none.

const renderCustomizedLabel = (...) => {
  ...
  return <g style={{ pointerEvents: 'none' }}>...</g>;
};

According to MDN, by setting pointer-events: none

The element is never the target of mouse events; however, mouse events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, mouse events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

Hence the click event passes through the label and triggers Pie onClick.

Upvotes: 5

Related Questions