
An interactive donut pie chart with month selection built with TanStack Charts.
components/tanstack-charts/pie/pie-interactive.tsx
import { type ChartPoint, defineChart } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { focusGroupAngle, pie, polar, radialArc, radialText } from "@tanstack/charts/polar";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo, useState } from "react";
import { scaleLinear } from "d3-scale";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
interface MonthDatum {
month: string;
visitors: number;
}
function generateDemoData(): MonthDatum[] {
return [
{ month: "january", visitors: 186 },
{ month: "february", visitors: 305 },
{ month: "march", visitors: 237 },
{ month: "april", visitors: 173 },
{ month: "may", visitors: 209 },
];
}
const monthNames = ["january", "february", "march", "april", "may"] as const;
const chartColors = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function titleCase(value: string) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
function extractDatumMetric(datum: unknown) {
if (!datum || typeof datum !== "object") return undefined;
const label =
Reflect.get(datum, "month") ??
Reflect.get(datum, "browser") ??
Reflect.get(datum, "category") ??
Reflect.get(datum, "label");
const visitors = Reflect.get(datum, "visitors") ?? Reflect.get(datum, "value");
return typeof label === "string" && typeof visitors === "number" && Number.isFinite(visitors)
? { label, visitors }
: undefined;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
const point = points.find((candidate) => extractDatumMetric(candidate.datum));
const metric = point && extractDatumMetric(point.datum);
return metric
? {
title: titleCase(metric.label),
rows: [
{
label: "Visitors",
value: metric.visitors.toLocaleString("en-US"),
color: point.color,
},
],
}
: { rows: [] };
}
export function PieInteractive() {
const data = useMemo(() => generateDemoData(), []);
const [activeMonth, setActiveMonth] = useState<string>("january");
const definition = useMemo(() => {
const arcs = pie(data, {
value: "visitors",
startAngle: Math.PI / 2,
endAngle: (-Math.PI * 3) / 2,
});
const activeIndex = Math.max(
0,
data.findIndex((row) => row.month === activeMonth),
);
const activeRow = data[activeIndex]!;
const active = arcs.filter((row) => row.month === activeRow.month);
const activeColor = chartColors[activeIndex]!;
return defineChart(
{
renderer: motionRenderer,
motion: {
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
},
scales: {
x: null,
y: null,
},
marks: [
polar({
radiusRatio: 0.78,
scales: {
angle: { scale: scaleLinear().domain([0, Math.PI * 2]) },
radius: { scale: scaleLinear().domain([0, 1]) },
},
marks: [
radialArc(arcs, {
id: "month-slices",
key: "month",
innerRadius: 60,
color: "month",
stroke: "var(--background)",
strokeWidth: 1,
}),
radialArc(active, {
id: "active-month",
key: "month",
innerRadius: 60,
outerRadius: ({ radius }) => radius + 10,
fill: activeColor,
stroke: "var(--background)",
strokeWidth: 5,
}),
radialArc(active, {
id: "active-month-ring",
key: "month",
innerRadius: ({ radius }) => radius + 12,
outerRadius: ({ radius }) => radius + 25,
fill: activeColor,
stroke: "var(--background)",
strokeWidth: 3,
}),
radialText(
[
{
id: "total",
angle: 0,
radius: 0,
text: String(activeRow.visitors),
},
],
{
id: "active-total",
angle: "angle",
radius: "radius",
key: "id",
text: "text",
dy: -5,
fill: "var(--foreground)",
fontSize: 30,
fontWeight: 700,
},
),
radialText([{ id: "label", angle: 0, radius: 0, text: "Visitors" }], {
id: "active-label",
angle: "angle",
radius: "radius",
key: "id",
text: "text",
dy: 20,
fill: "var(--muted-foreground)",
fontSize: 12,
}),
],
}),
],
color: {
domain: monthNames,
range: chartColors,
},
margin: 0,
},
{
focus: focusGroupAngle,
tooltip: {
use: tooltip,
motion: { type: "spring", stiffness: 170, damping: 18 },
className: "font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
sort: "color-domain",
content: (points) => shadcnTooltipContent(points),
},
},
);
}, [data, activeMonth]);
return (
<Card className="flex w-full max-w-md flex-col">
<CardHeader className="flex-row items-center justify-between space-y-0 pb-2">
<div className="grid gap-1">
<CardTitle>Traffic Source Attribution</CardTitle>
<CardDescription>User acquisition distribution across marketing channels</CardDescription>
</div>
<Select value={activeMonth} onValueChange={(val) => val && setActiveMonth(val)}>
<SelectTrigger size="sm" className="w-[130px] cursor-pointer rounded-lg" aria-label="Select month">
<SelectValue placeholder="Select month" />
</SelectTrigger>
<SelectContent align="end" className="rounded-xl">
{data.map((row, index) => (
<SelectItem key={row.month} value={row.month} className="cursor-pointer rounded-lg">
<span className="flex items-center gap-2">
<span
className="size-2 shrink-0 rounded-full"
style={{ backgroundColor: chartColors[index] }}
/>
<span>{titleCase(row.month)}</span>
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</CardHeader>
<CardContent className="flex-1 pb-0">
<div className="mx-auto flex aspect-square max-h-[250px] w-full items-center justify-center">
<Chart
definition={definition}
renderer={motionRenderer}
initialWidth={250}
height={250}
ariaLabel="Traffic Source Attribution Chart"
/>
</div>
</CardContent>
</Card>
);
}
export default PieInteractive;