Animating Pie Chart Slices in Recharts: A Step-by-Step Guide

1) Introduction

Animating pie slices is a simple yet effective way to draw attention and make data visualization more interactive. The best part? You only need CSS to get it done. Hover over the slices below and see how it works in action!

  • Food
  • Transport
  • Shopping

2) Code and Examples

The secret behind animating pie slices lies in rendering each slice individually with the Cell component and applying CSS for hover animations. This approach ensures smooth transitions without the need for JavaScript-based animations

"use client"

import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";
import { data } from "./data";

export default function Chart() {
  return (
    <div className="size-64">
      <ResponsiveContainer>
        <PieChart margin={{ left: 0, right: 0, bottom: 0, top: 0 }}>
          <Pie
            dataKey="value"
            data={data}
            blendStroke
            className="focus:outline-none"
            animationDuration={600}
            animationBegin={0}
            animationEasing="ease-out"
            labelLine={false}
            innerRadius="45%"
            outerRadius="95%"
          >
            {data.map((entry, i) => (
              <Cell
                key={`cell-${i}`}
                fill={entry.fill}
                className="origin-center outline-none transition-transform duration-[250ms]
                ease-out hover:scale-105 focus:outline-none"
              />
             ))}
          </Pie>
        </PieChart>
      </ResponsiveContainer>
    </div>
   );
}

How Does It Work

How does the animation work? First take look at theouterRadius property on the Pie component. It's currently set as 95% of the available space. This sets a margin around our chart that we can use for growing each cell on hover.

  • origin-center — Sets the transform-origin to start from center of the element.
  • hover:scale-105 — This will scale the element to 105% of it's size upon hovering.

Data From The Example

type Data = {
  name: string;
  value: number;
  fill: string;
}

const data: Data[] = [
  {
    name: "Food",
    value: 250,
    fill: "#F1F1F1",
  },
  {
    name: "Transport",
    value: 250,
    fill: "#FF7141",
  },
  {
    name: "Shopping",
    value: 500,
    fill: "#5A5771",
  },
];

export default data;