Blog>
Snippets

Integrating Interactivity in Pie Charts

Illustrate how to add interactivity to a pie chart, such as hover effects that display additional data details or implementing click events that drill down into more detailed datasets.
import React, { useState } from 'react';
import { PieChart, Pie, Tooltip, Cell } from 'recharts';
Imports necessary components from React and Recharts.
const data = [
  { name: 'Group A', value: 400 },
  { name: 'Group B', value: 300 },
  { name: 'Group C', value: 300 },
  { name: 'Group D', value: 200 },
];
Defines the data to be used in the pie chart.
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
Defines the colors for each sector of the pie chart.
const InteractivePieChart = () => {
  const [activeIndex, setActiveIndex] = useState(null);

  const onPieEnter = (_, index) => {
    setActiveIndex(index);
  };

  const onPieLeave = () => {
    setActiveIndex(null);
  };

  return (
    <PieChart width={400} height={400}>
      <Pie
        data={data}
        cx={'50%'}
        cy={'50%'}
        innerRadius={60}
        outerRadius={80}
        fill="#8884d8"
        onMouseEnter={onPieEnter}
        onMouseLeave={onPieLeave}
      >
        {data.map((entry, index) => (
          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
        ))}
      </Pie>
      <Tooltip />
    </PieChart>
  );
};
Creates an interactive PieChart component with hover effects. On hovering a slice, it stores the active slice index. The slices change their appearance based on the hover state.
export default InteractivePieChart;
Exports the InteractivePieChart component for use in other parts of the application.