Chart
Animated React charts built on shadcn/ui and Recharts v3: themed ChartContainer, tooltip and legend helpers for dark dashboards, plus an area chart with soft fills that draw in, a bar chart with hover highlights and a radial progress stat that counts up.
- Drop-in shadcn API
- Recharts v3
- Themed tooltips
- Accessible data tables
- prefers-reduced-motion
Visitors
Unique visitors per day
| date | Desktop | Mobile |
|---|---|---|
| Oct 25 | 339 | 259 |
| Oct 26 | 321 | 280 |
| Oct 27 | 300 | 295 |
| Oct 28 | 279 | 300 |
| Oct 29 | 263 | 294 |
| Oct 30 | 254 | 279 |
| Oct 31 | 254 | 260 |
| Nov 1 | 263 | 243 |
| Nov 2 | 279 | 232 |
| Nov 3 | 301 | 230 |
| Nov 4 | 325 | 235 |
| Nov 5 | 347 | 242 |
| Nov 6 | 366 | 245 |
| Nov 7 | 378 | 240 |
| Nov 8 | 385 | 227 |
| Nov 9 | 386 | 208 |
| Nov 10 | 384 | 188 |
| Nov 11 | 382 | 174 |
| Nov 12 | 382 | 169 |
| Nov 13 | 388 | 176 |
| Nov 14 | 399 | 192 |
| Nov 15 | 415 | 212 |
| Nov 16 | 436 | 231 |
| Nov 17 | 457 | 243 |
| Nov 18 | 477 | 247 |
| Nov 19 | 491 | 245 |
| Nov 20 | 498 | 241 |
| Nov 21 | 496 | 240 |
| Nov 22 | 485 | 246 |
| Nov 23 | 467 | 262 |
"use client";
import { AreaChartCard } from "@/components/dusk/chart/area-chart";
import type { ChartConfig } from "@/components/ui/chart";
const DAY = 86_400_000;
const start = Date.UTC(2026, 7, 26);
// Deterministic demo data (no Math.random), so server and client agree.
const data = Array.from({ length: 90 }, (_, i) => ({
date: new Date(start + i * DAY).toISOString().slice(0, 10),
desktop: Math.round(240 + 70 * Math.sin(i / 6) + 35 * Math.sin(i / 2.2) + i * 1.8),
mobile: Math.round(150 + 50 * Math.cos(i / 5) + 25 * Math.sin(i / 1.6) + i * 1.2),
}));
const config = {
desktop: { label: "Desktop", color: "var(--chart-1)" },
mobile: { label: "Mobile", color: "var(--chart-3)" },
} satisfies ChartConfig;
const dateFormat = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
export default function AreaChartDemo() {
return (
<AreaChartCard
className="max-w-2xl"
title="Visitors"
description="Unique visitors per day"
data={data}
config={config}
index="date"
ranges={[
{ label: "7d", points: 7 },
{ label: "30d", points: 30 },
{ label: "90d", points: 90 },
]}
defaultRange="30d"
labelFormatter={(value) => dateFormat.format(new Date(`${value}T00:00:00Z`))}
/>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/chart.json1. Install the dependencies.
npm install recharts2. Copy the source into
components/ui/chart.tsx.chart.tsx "use client" import * as React from "react" import * as RechartsPrimitive from "recharts" import type { LegendPayload, TooltipPayloadEntry } from "recharts" import { cn } from "@/lib/utils" /** * DuskUI Chart — the shadcn/ui Chart helpers on Recharts v3, themed for DuskUI. * * Same API as shadcn (ChartContainer, ChartTooltip, ChartTooltipContent, * ChartLegend, ChartLegendContent, ChartStyle, ChartConfig), plus: * - Axis ticks, grid lines, cursors and active dots use the DuskUI tokens, so * charts sit on the dark surface without extra styling. * - A solid tooltip with a hairline border, tabular numbers and an * indicator that matches each series color. * - `ChartContainer` is a labelled `figure` when you pass `title`, and keeps * Recharts' keyboard accessibility layer (arrow keys move the tooltip). * - `useChartReducedMotion()` returns `true` under `prefers-reduced-motion`, * so you can pass `isAnimationActive={!reduced}` to series and tooltips. * Colors come from the config as CSS variables: a series keyed `desktop` * reads `var(--color-desktop)`. */ // Format: { THEME_NAME: CSS_SELECTOR } const THEMES = { light: "", dark: ".dark" } as const export type ChartConfig = { [k in string]: { label?: React.ReactNode icon?: React.ComponentType } & ( | { color?: string; theme?: never } | { color?: never; theme: Record<keyof typeof THEMES, string> } ) } type ChartContextProps = { config: ChartConfig } const ChartContext = React.createContext<ChartContextProps | null>(null) /** Reads the nearest ChartContainer's config. */ function useChart() { const context = React.useContext(ChartContext) if (!context) { throw new Error("useChart must be used within a <ChartContainer />") } return context } const reducedMotionQuery = "(prefers-reduced-motion: reduce)" function subscribeReducedMotion(onChange: () => void) { const mql = window.matchMedia(reducedMotionQuery) mql.addEventListener("change", onChange) return () => mql.removeEventListener("change", onChange) } /** * `true` when the user prefers reduced motion. `false` on the server and * during hydration, so markup always matches; charts only draw on the client. */ function useChartReducedMotion() { return React.useSyncExternalStore( subscribeReducedMotion, () => window.matchMedia(reducedMotionQuery).matches, () => false ) } /** Sizes the chart to its box, injects the config colors and themes Recharts. */ function ChartContainer({ id, className, children, config, title, ...props }: React.ComponentProps<"div"> & { config: ChartConfig /** Accessible name for the chart. Renders the container as role="figure". */ title?: string children: React.ComponentProps< typeof RechartsPrimitive.ResponsiveContainer >["children"] }) { const uniqueId = React.useId() const chartId = `chart-${id ?? uniqueId.replace(/[^a-zA-Z0-9_-]/g, "")}` return ( <ChartContext.Provider value={{ config }}> <div data-slot="chart" data-chart={chartId} role={title ? "figure" : undefined} aria-label={title} className={cn( "flex aspect-video justify-center text-xs", "[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground", "[&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-white/[0.06]", "[&_.recharts-curve.recharts-tooltip-cursor]:stroke-white/20", "[&_.recharts-polar-grid_[stroke='#ccc']]:stroke-white/10", "[&_.recharts-radial-bar-background-sector]:fill-white/[0.05]", "[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-white/[0.04]", "[&_.recharts-reference-line_[stroke='#ccc']]:stroke-white/10", "[&_.recharts-dot[stroke='#fff']]:stroke-background", "[&_.recharts-sector[stroke='#fff']]:stroke-background", "[&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-surface]:outline-hidden", "[&_.recharts-wrapper:has(.recharts-surface:focus-visible)]:rounded-md [&_.recharts-wrapper:has(.recharts-surface:focus-visible)]:ring-2 [&_.recharts-wrapper:has(.recharts-surface:focus-visible)]:ring-ring/50", className )} {...props} > <ChartStyle id={chartId} config={config} /> <RechartsPrimitive.ResponsiveContainer> {children} </RechartsPrimitive.ResponsiveContainer> </div> </ChartContext.Provider> ) } /** Writes `--color-<key>` variables for every config entry, scoped to one chart. */ function ChartStyle({ id, config }: { id: string; config: ChartConfig }) { const colorConfig = Object.entries(config).filter( ([, itemConfig]) => itemConfig.theme || itemConfig.color ) if (!colorConfig.length) { return null } return ( <style dangerouslySetInnerHTML={{ __html: Object.entries(THEMES) .map( ([theme, prefix]) => ` ${prefix} [data-chart="${id}"] { ${colorConfig .map(([key, itemConfig]) => { const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ?? itemConfig.color return color ? ` --color-${key}: ${color};` : null }) .filter(Boolean) .join("\n")} } ` ) .join("\n"), }} /> ) } /** Recharts' Tooltip. Pass `content={<ChartTooltipContent />}`. */ const ChartTooltip = RechartsPrimitive.Tooltip type ChartTooltipContentProps = { /** Injected by Recharts. */ active?: boolean /** Injected by Recharts. */ payload?: ReadonlyArray<TooltipPayloadEntry> /** Injected by Recharts. */ label?: React.ReactNode className?: string /** Hide the heading (the x value / category). */ hideLabel?: boolean /** Hide the colored swatch next to each value. */ hideIndicator?: boolean indicator?: "line" | "dot" | "dashed" /** Payload key to look up the series label in the config. */ nameKey?: string /** Data key to look up the heading in the config. */ labelKey?: string labelFormatter?: ( label: React.ReactNode, payload: ReadonlyArray<TooltipPayloadEntry> ) => React.ReactNode labelClassName?: string formatter?: ( value: TooltipPayloadEntry["value"], name: TooltipPayloadEntry["name"], item: TooltipPayloadEntry, index: number, payload: TooltipPayloadEntry["payload"] ) => React.ReactNode /** Force one indicator color for every row. */ color?: string } /** The DuskUI tooltip surface: frosted, hairline border, tabular numbers. */ function ChartTooltipContent({ active, payload, className, indicator = "dot", hideLabel = false, hideIndicator = false, label, labelFormatter, labelClassName, formatter, color, nameKey, labelKey, }: ChartTooltipContentProps) { const { config } = useChart() const tooltipLabel = React.useMemo(() => { if (hideLabel || !payload?.length) { return null } const [item] = payload const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}` const itemConfig = getPayloadConfigFromPayload(config, item, key) const value = !labelKey && typeof label === "string" ? (config[label]?.label ?? label) : itemConfig?.label if (labelFormatter) { return ( <div className={cn("font-medium text-foreground", labelClassName)}> {labelFormatter(value ?? label, payload)} </div> ) } if (!value) { return null } return <div className={cn("font-medium text-foreground", labelClassName)}>{value}</div> }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]) if (!active || !payload?.length) { return null } const nestLabel = payload.length === 1 && indicator !== "dot" return ( <div data-slot="chart-tooltip" className={cn( "grid min-w-32 items-start gap-1.5 rounded-lg border bg-popover px-2.5 py-1.5 text-xs shadow-md", className )} > {!nestLabel ? tooltipLabel : null} <div className="grid gap-1.5"> {payload .filter((item) => item.type !== "none") .map((item, index) => { const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}` const itemConfig = getPayloadConfigFromPayload(config, item, key) const indicatorColor = color ?? (item.payload as { fill?: string } | undefined)?.fill ?? item.color return ( <div key={`${item.dataKey ?? index}`} className={cn( "flex w-full flex-wrap items-stretch gap-2 [&>svg]:size-2.5 [&>svg]:text-muted-foreground", indicator === "dot" && "items-center" )} > {formatter && item.value !== undefined && item.name !== undefined ? ( formatter(item.value, item.name, item, index, item.payload) ) : ( <> {itemConfig?.icon ? ( <itemConfig.icon /> ) : ( !hideIndicator && ( <div aria-hidden className={cn( "shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)", { "size-2.5 rounded-full": indicator === "dot", "w-1": indicator === "line", "w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed", "my-0.5": nestLabel && indicator === "dashed", } )} style={ { "--color-bg": indicatorColor, "--color-border": indicatorColor, } as React.CSSProperties } /> ) )} <div className={cn( "flex flex-1 justify-between gap-4 leading-none", nestLabel ? "items-end" : "items-center" )} > <div className="grid gap-1.5"> {nestLabel ? tooltipLabel : null} <span className="text-muted-foreground"> {itemConfig?.label ?? item.name} </span> </div> {item.value !== undefined && item.value !== null && ( <span className="font-mono font-medium text-foreground tabular-nums"> {typeof item.value === "number" ? item.value.toLocaleString() : String(item.value)} </span> )} </div> </> )} </div> ) })} </div> </div> ) } /** Recharts' Legend. Pass `content={<ChartLegendContent />}`. */ const ChartLegend = RechartsPrimitive.Legend /** A row of swatches and labels taken from the chart config. */ function ChartLegendContent({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey, }: { className?: string /** Hide the swatch (or the config icon). */ hideIcon?: boolean /** Injected by Recharts. */ payload?: ReadonlyArray<LegendPayload> /** Injected by Recharts. */ verticalAlign?: "top" | "bottom" | "middle" /** Payload key to look up the series label in the config. */ nameKey?: string }) { const { config } = useChart() if (!payload?.length) { return null } return ( <ul data-slot="chart-legend" className={cn( "flex flex-wrap items-center justify-center gap-x-4 gap-y-1.5", verticalAlign === "top" ? "pb-3" : "pt-3", className )} > {payload .filter((item) => item.type !== "none") .map((item) => { const key = `${nameKey ?? item.dataKey ?? "value"}` const itemConfig = getPayloadConfigFromPayload(config, item, key) return ( <li key={`${item.value ?? key}`} className={cn( "flex items-center gap-1.5 text-muted-foreground [&>svg]:size-3 [&>svg]:text-muted-foreground", item.inactive && "opacity-50" )} > {itemConfig?.icon && !hideIcon ? ( <itemConfig.icon /> ) : ( !hideIcon && ( <span aria-hidden className="size-2 shrink-0 rounded-[2px]" style={{ backgroundColor: item.color }} /> ) )} {itemConfig?.label ?? item.value} </li> ) })} </ul> ) } /** Finds the config entry for a tooltip / legend item. */ function getPayloadConfigFromPayload( config: ChartConfig, payload: unknown, key: string ) { if (typeof payload !== "object" || payload === null) { return undefined } const payloadPayload = "payload" in payload && typeof payload.payload === "object" && payload.payload !== null ? payload.payload : undefined let configLabelKey: string = key if ( key in payload && typeof payload[key as keyof typeof payload] === "string" ) { configLabelKey = payload[key as keyof typeof payload] as string } else if ( payloadPayload && key in payloadPayload && typeof payloadPayload[key as keyof typeof payloadPayload] === "string" ) { configLabelKey = payloadPayload[ key as keyof typeof payloadPayload ] as string } return configLabelKey in config ? config[configLabelKey] : config[key] } export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle, useChart, useChartReducedMotion, }
Adds components/ui/chart.tsx with the shadcn exports, typed for Recharts v3. Each config entry becomes a CSS variable scoped to its chart (desktop → var(--color-desktop)). useChartReducedMotion() is exported so you can pass isAnimationActive explicitly.
Usage
"use client"
import { Bar, BarChart, XAxis } from "recharts"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
useChartReducedMotion,
type ChartConfig,
} from "@/components/ui/chart"
const data = [
{ month: "Jan", desktop: 186 },
{ month: "Feb", desktop: 305 },
]
const config = {
desktop: { label: "Desktop", color: "var(--chart-1)" },
} satisfies ChartConfig
export function VisitorsChart() {
const reduced = useChartReducedMotion()
return (
<ChartContainer config={config} title="Desktop visitors" className="h-56 w-full">
<BarChart data={data}>
<XAxis dataKey="month" tickLine={false} axisLine={false} />
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} isAnimationActive={!reduced} />
</BarChart>
</ChartContainer>
)
}Examples
Default
A grouped bar chart with ChartTooltipContent and ChartLegendContent. Labels and colors come from the config, and axis ticks and grid lines pick up the DuskUI tokens.
"use client";
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
import {
ChartContainer,
ChartLegend,
ChartLegendContent,
ChartTooltip,
ChartTooltipContent,
useChartReducedMotion,
type ChartConfig,
} from "@/components/ui/chart";
const data = [
{ month: "Jan", desktop: 186, mobile: 80 },
{ month: "Feb", desktop: 305, mobile: 200 },
{ month: "Mar", desktop: 237, mobile: 120 },
{ month: "Apr", desktop: 173, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "Jun", desktop: 214, mobile: 140 },
];
const config = {
desktop: { label: "Desktop", color: "var(--chart-1)" },
mobile: { label: "Mobile", color: "var(--chart-3)" },
} satisfies ChartConfig;
export default function ChartBasicDemo() {
const reduced = useChartReducedMotion();
return (
<ChartContainer config={config} title="Visitors by device, January to June" className="min-h-[220px] w-full max-w-lg">
<BarChart data={data}>
<CartesianGrid vertical={false} />
<XAxis dataKey="month" tickLine={false} tickMargin={10} axisLine={false} />
<ChartTooltip cursor={false} content={<ChartTooltipContent />} isAnimationActive={!reduced} />
<ChartLegend content={<ChartLegendContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} isAnimationActive={!reduced} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} isAnimationActive={!reduced} />
</BarChart>
</ChartContainer>
);
}Line indicator tooltip
indicator switches the tooltip swatch between dot, line and dashed. Focus the chart and use the arrow keys to move the tooltip — Recharts' accessibility layer is on by default in v3.
"use client";
import { CartesianGrid, Line, LineChart, XAxis } from "recharts";
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
useChartReducedMotion,
type ChartConfig,
} from "@/components/ui/chart";
const data = [
{ week: "W1", p50: 120, p95: 310 },
{ week: "W2", p50: 112, p95: 284 },
{ week: "W3", p50: 128, p95: 352 },
{ week: "W4", p50: 104, p95: 260 },
{ week: "W5", p50: 98, p95: 241 },
{ week: "W6", p50: 95, p95: 232 },
{ week: "W7", p50: 101, p95: 247 },
];
const config = {
p50: { label: "p50 latency (ms)", color: "var(--chart-1)" },
p95: { label: "p95 latency (ms)", color: "var(--chart-4)" },
} satisfies ChartConfig;
export default function ChartLineTooltipDemo() {
const reduced = useChartReducedMotion();
return (
<ChartContainer config={config} title="API latency over seven weeks" className="aspect-auto h-56 w-full max-w-lg">
<LineChart data={data} margin={{ left: 12, right: 12, top: 8 }}>
<CartesianGrid vertical={false} />
<XAxis dataKey="week" tickLine={false} axisLine={false} tickMargin={8} />
<ChartTooltip content={<ChartTooltipContent indicator="line" />} isAnimationActive={!reduced} />
{(["p50", "p95"] as const).map((key) => (
<Line
key={key}
dataKey={key}
type="monotone"
stroke={`var(--color-${key})`}
strokeWidth={2}
dot={false}
activeDot={{ r: 4, fill: `var(--color-${key})`, stroke: "var(--color-background)", strokeWidth: 2 }}
isAnimationActive={!reduced}
/>
))}
</LineChart>
</ChartContainer>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Area Chart
A dashboard card with softly filled areas that draw in from the left, a readout that follows the pointer or keyboard, and range buttons with a gliding pill. The readout has a fixed height, so hovering never shifts the layout. A visually hidden table carries the numbers for screen readers.
Visitors
Unique visitors per day
| date | Desktop | Mobile |
|---|---|---|
| Oct 25 | 339 | 259 |
| Oct 26 | 321 | 280 |
| Oct 27 | 300 | 295 |
| Oct 28 | 279 | 300 |
| Oct 29 | 263 | 294 |
| Oct 30 | 254 | 279 |
| Oct 31 | 254 | 260 |
| Nov 1 | 263 | 243 |
| Nov 2 | 279 | 232 |
| Nov 3 | 301 | 230 |
| Nov 4 | 325 | 235 |
| Nov 5 | 347 | 242 |
| Nov 6 | 366 | 245 |
| Nov 7 | 378 | 240 |
| Nov 8 | 385 | 227 |
| Nov 9 | 386 | 208 |
| Nov 10 | 384 | 188 |
| Nov 11 | 382 | 174 |
| Nov 12 | 382 | 169 |
| Nov 13 | 388 | 176 |
| Nov 14 | 399 | 192 |
| Nov 15 | 415 | 212 |
| Nov 16 | 436 | 231 |
| Nov 17 | 457 | 243 |
| Nov 18 | 477 | 247 |
| Nov 19 | 491 | 245 |
| Nov 20 | 498 | 241 |
| Nov 21 | 496 | 240 |
| Nov 22 | 485 | 246 |
| Nov 23 | 467 | 262 |
"use client";
import { AreaChartCard } from "@/components/dusk/chart/area-chart";
import type { ChartConfig } from "@/components/ui/chart";
const DAY = 86_400_000;
const start = Date.UTC(2026, 7, 26);
// Deterministic demo data (no Math.random), so server and client agree.
const data = Array.from({ length: 90 }, (_, i) => ({
date: new Date(start + i * DAY).toISOString().slice(0, 10),
desktop: Math.round(240 + 70 * Math.sin(i / 6) + 35 * Math.sin(i / 2.2) + i * 1.8),
mobile: Math.round(150 + 50 * Math.cos(i / 5) + 25 * Math.sin(i / 1.6) + i * 1.2),
}));
const config = {
desktop: { label: "Desktop", color: "var(--chart-1)" },
mobile: { label: "Mobile", color: "var(--chart-3)" },
} satisfies ChartConfig;
const dateFormat = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
export default function AreaChartDemo() {
return (
<AreaChartCard
className="max-w-2xl"
title="Visitors"
description="Unique visitors per day"
data={data}
config={config}
index="date"
ranges={[
{ label: "7d", points: 7 },
{ label: "30d", points: 30 },
{ label: "90d", points: 90 },
]}
defaultRange="30d"
labelFormatter={(value) => dateFormat.format(new Date(`${value}T00:00:00Z`))}
/>
);
}$ npx shadcn@latest add https://duskui.com/r/area-chart.json1. Install the dependencies.
npm install motion recharts2. Copy the source into
components/dusk/chart/area-chart.tsx.area-chart.tsx "use client"; import * as React from "react"; import { Area, AreaChart as RechartsAreaChart, CartesianGrid, XAxis, YAxis } from "recharts"; import { LayoutGroup, motion, useReducedMotion } from "motion/react"; import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig, } from "@/components/ui/chart"; import { cn } from "@/lib/utils"; type Datum = Record<string, string | number>; export interface ChartRange { /** Button text, e.g. "7d". */ label: string; /** How many trailing data points the range shows. */ points: number; } export interface AreaChartCardProps extends Omit<React.ComponentProps<"section">, "title"> { title: React.ReactNode; description?: React.ReactNode; /** Rows of data, oldest first. Keep it static or memoized. */ data: Datum[]; /** One entry per series: `{ desktop: { label, color } }`. Order sets the stack order. */ config: ChartConfig; /** Key of the x value (a date or category). */ index: string; /** Range buttons that show the last N points. Omit to show everything. */ ranges?: ChartRange[]; defaultRange?: string; /** Stack the series instead of overlapping them. */ stacked?: boolean; /** Formats x values for ticks, the tooltip and the readout. */ labelFormatter?: (value: string | number) => string; /** Formats y values. Defaults to en-US grouping (stable across server and client). */ valueFormatter?: (value: number) => string; /** Accessible name for the chart. Defaults to the title when it is a string. */ chartLabel?: string; } const numberFormat = new Intl.NumberFormat("en-US"); /** The config color for a series (the CSS variables only exist inside the chart). */ function seriesColor(config: ChartConfig, key: string) { const entry = config[key]; return entry?.color ?? entry?.theme?.dark ?? "currentColor"; } const defaultValueFormatter = (value: number) => numberFormat.format(value); /** * An area chart card with soft fills that draw in from the left, a * readout that follows the pointer (or the keyboard: focus the chart and use * the arrow keys), and range buttons with a gliding pill. Series colors come * from the chart config. A visually hidden table carries the same numbers * for screen readers. Recharts animation is off under reduced motion. */ export function AreaChartCard({ title, description, data, config, index, ranges, defaultRange, stacked = false, labelFormatter = String, valueFormatter = defaultValueFormatter, chartLabel, className, ...props }: AreaChartCardProps) { const uid = React.useId().replace(/[^a-zA-Z0-9]/g, ""); const reduceMotion = useReducedMotion() ?? false; const [range, setRange] = React.useState(defaultRange ?? ranges?.[ranges.length - 1]?.label); const [active, setActive] = React.useState<number | null>(null); const keys = Object.keys(config); const points = ranges?.find((r) => r.label === range)?.points ?? data.length; const visible = React.useMemo(() => data.slice(-points), [data, points]); const row = visible[active ?? visible.length - 1]; const label = typeof title === "string" ? title : chartLabel; return ( <section className={cn( "w-full rounded-xl border bg-card p-5 text-card-foreground", className )} {...props} > <header className="flex flex-wrap items-start justify-between gap-4"> <div className="min-w-0"> <h3 className="text-sm font-medium text-muted-foreground">{title}</h3> {description && <p className="mt-0.5 text-xs text-muted-foreground/80">{description}</p>} </div> {ranges && ranges.length > 1 && ( <LayoutGroup id={uid}> <div role="group" aria-label="Date range" className="flex rounded-lg border bg-background/60 p-0.5"> {ranges.map((r) => { const selected = r.label === range; return ( <button key={r.label} type="button" aria-pressed={selected} onClick={() => { setRange(r.label); setActive(null); }} className={cn( "relative rounded-md px-2.5 py-1 text-xs font-medium outline-none transition-colors", "focus-visible:ring-[3px] focus-visible:ring-ring/50", selected ? "text-foreground" : "text-muted-foreground hover:text-foreground" )} > {selected && ( <motion.span layoutId="range-pill" className="absolute inset-0 rounded-md bg-white/[0.08]" transition={reduceMotion ? { duration: 0 } : { type: "spring", stiffness: 500, damping: 36 }} /> )} <span className="relative">{r.label}</span> </button> ); })} </div> </LayoutGroup> )} </header> {/* Readout: fixed height so hovering never shifts the layout. */} <div className="mt-3 flex min-h-12 flex-wrap items-end gap-x-6 gap-y-1" aria-hidden> {keys.map((key) => ( <div key={key} className="flex flex-col"> <span className="flex items-center gap-1.5 text-xs text-muted-foreground"> <span className="size-2 rounded-[2px]" style={{ backgroundColor: seriesColor(config, key) }} /> {config[key]?.label ?? key} </span> <span className="text-2xl font-semibold tracking-tight tabular-nums"> {row ? valueFormatter(Number(row[key] ?? 0)) : "—"} </span> </div> ))} <span className="ml-auto pb-1 text-xs text-muted-foreground tabular-nums"> {row ? labelFormatter(row[index]) : ""} </span> </div> <ChartContainer config={config} title={label} className="mt-4 aspect-auto h-60 w-full" > <RechartsAreaChart data={visible} margin={{ left: 0, right: 8, top: 8, bottom: 0 }} onMouseMove={(state) => { const i = Number(state.activeTooltipIndex); setActive(Number.isFinite(i) && state.isTooltipActive ? i : null); }} onMouseLeave={() => setActive(null)} > <defs> {keys.map((key) => ( <linearGradient key={key} id={`${uid}-fill-${key}`} x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" stopColor={`var(--color-${key})`} stopOpacity={0.25} /> <stop offset="70%" stopColor={`var(--color-${key})`} stopOpacity={0.04} /> <stop offset="100%" stopColor={`var(--color-${key})`} stopOpacity={0} /> </linearGradient> ))} </defs> <CartesianGrid vertical={false} /> <XAxis dataKey={index} tickLine={false} axisLine={false} tickMargin={8} minTickGap={28} tickFormatter={(value) => labelFormatter(value)} /> <YAxis tickLine={false} axisLine={false} tickMargin={4} width={40} tickFormatter={(value) => valueFormatter(Number(value))} /> <ChartTooltip cursor={{ strokeDasharray: "3 3" }} isAnimationActive={!reduceMotion} content={ <ChartTooltipContent indicator="dot" labelFormatter={(_, payload) => { const x = payload[0]?.payload?.[index]; return x === undefined ? null : labelFormatter(x); }} /> } /> {[...keys].reverse().map((key) => ( <Area key={key} dataKey={key} type="monotone" stroke={`var(--color-${key})`} strokeWidth={2} fill={`url(#${uid}-fill-${key})`} stackId={stacked ? "stack" : undefined} activeDot={{ r: 4, strokeWidth: 2, stroke: "var(--color-background)", fill: `var(--color-${key})` }} isAnimationActive={!reduceMotion} animationDuration={1100} animationEasing="ease-out" /> ))} {keys.length > 1 && <ChartLegend content={<ChartLegendContent />} />} </RechartsAreaChart> </ChartContainer> <table className="sr-only"> <caption>{label}</caption> <thead> <tr> <th scope="col">{index}</th> {keys.map((key) => ( <th key={key} scope="col"> {typeof config[key]?.label === "string" ? config[key]?.label : key} </th> ))} </tr> </thead> <tbody> {visible.map((d, i) => ( <tr key={i}> <th scope="row">{labelFormatter(d[index])}</th> {keys.map((key) => ( <td key={key}>{valueFormatter(Number(d[key] ?? 0))}</td> ))} </tr> ))} </tbody> </table> </section> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| title / description | ReactNode | — | Card heading. A string title also names the chart. |
| data | Record<string, string | number>[] | — | Rows, oldest first. Keep it static or memoized. |
| config | ChartConfig | — | One entry per series; keys are data keys. |
| index | string | — | Key of the x value. |
| ranges / defaultRange | { label, points }[] / string | — | Range buttons that show the last N points. |
| stacked | boolean | false | Stack the series instead of overlapping. |
| labelFormatter / valueFormatter | (value) => string | — | Format x and y values. Use fixed locales to keep SSR stable. |
| chartLabel | string | — | Accessible name when the title isn't a string. |
Bar Chart
Hovering a bar dims the others, outlines the hovered one and swaps the headline to its value. Bars grow in on mount, and the keyboard-active bar is outlined the same way.
Monthly revenue
January – August 2026
| month | Revenue |
|---|---|
| Jan | $18,400 |
| Feb | $21,900 |
| Mar | $19,300 |
| Apr | $26,700 |
| May | $24,100 |
| Jun | $31,200 |
| Jul | $29,800 |
| Aug | $34,600 |
"use client";
import { BarChartCard } from "@/components/dusk/chart/bar-chart";
import type { ChartConfig } from "@/components/ui/chart";
const data = [
{ month: "Jan", revenue: 18_400 },
{ month: "Feb", revenue: 21_900 },
{ month: "Mar", revenue: 19_300 },
{ month: "Apr", revenue: 26_700 },
{ month: "May", revenue: 24_100 },
{ month: "Jun", revenue: 31_200 },
{ month: "Jul", revenue: 29_800 },
{ month: "Aug", revenue: 34_600 },
];
const config = {
revenue: { label: "Revenue", color: "var(--chart-1)" },
} satisfies ChartConfig;
const currency = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
export default function BarChartDemo() {
return (
<BarChartCard
className="max-w-xl"
title="Monthly revenue"
description="January – August 2026"
data={data}
config={config}
index="month"
dataKey="revenue"
valueFormatter={(value) => currency.format(value)}
/>
);
}$ npx shadcn@latest add https://duskui.com/r/bar-chart.json1. Install the dependencies.
npm install motion recharts2. Copy the source into
components/dusk/chart/bar-chart.tsx.bar-chart.tsx "use client"; import * as React from "react"; import { Bar, BarChart as RechartsBarChart, CartesianGrid, Rectangle, XAxis, type BarShapeProps } from "recharts"; import { useReducedMotion } from "motion/react"; import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart"; import { cn } from "@/lib/utils"; type Datum = Record<string, string | number>; export interface BarChartCardProps extends Omit<React.ComponentProps<"section">, "title"> { title: React.ReactNode; description?: React.ReactNode; data: Datum[]; /** Must contain `dataKey`: `{ revenue: { label, color } }`. */ config: ChartConfig; /** Key of the category (x) value. */ index: string; /** Key of the value to plot. */ dataKey: string; /** Formats values. Defaults to en-US grouping (stable across server and client). */ valueFormatter?: (value: number) => string; /** What the headline shows when nothing is hovered. */ summary?: "total" | "average" | "last"; /** Accessible name for the chart. Defaults to the title when it is a string. */ chartLabel?: string; } const numberFormat = new Intl.NumberFormat("en-US"); const defaultValueFormatter = (value: number) => numberFormat.format(value); /** * A bar chart card where hovering a bar dims the others and swaps the * headline to its value. Bars grow in on mount (off under reduced motion). * Keyboard users can focus the chart and arrow through bars; the active bar * gets the same crisp 1px outline as a hovered one. A visually * hidden table carries the numbers for screen readers. */ export function BarChartCard({ title, description, data, config, index, dataKey, valueFormatter = defaultValueFormatter, summary = "total", chartLabel, className, ...props }: BarChartCardProps) { const reduceMotion = useReducedMotion() ?? false; const [hovered, setHovered] = React.useState<number | null>(null); const label = typeof title === "string" ? title : chartLabel; const seriesLabel = config[dataKey]?.label ?? dataKey; const values = data.map((d) => Number(d[dataKey] ?? 0)); const total = values.reduce((sum, v) => sum + v, 0); const headline = hovered !== null ? values[hovered] : summary === "total" ? total : summary === "average" ? Math.round(total / Math.max(1, values.length)) : values[values.length - 1]; const caption = hovered !== null ? String(data[hovered]?.[index] ?? "") : summary === "total" ? "Total" : summary === "average" ? "Average" : "Latest"; const renderBar = React.useCallback( (shape: BarShapeProps) => { const dimmed = hovered !== null && shape.index !== hovered; const lit = shape.isActive || shape.index === hovered; return ( <Rectangle x={shape.x} y={shape.y} width={shape.width} height={shape.height} radius={[6, 6, 2, 2]} fill={`var(--color-${dataKey})`} fillOpacity={dimmed ? 0.28 : 1} stroke={lit ? "rgb(255 255 255 / 0.4)" : "none"} strokeWidth={1} style={{ transition: reduceMotion ? undefined : "fill-opacity 200ms ease-out", }} /> ); }, [hovered, dataKey, reduceMotion] ); return ( <section className={cn( "w-full rounded-xl border bg-card p-5 text-card-foreground", className )} {...props} > <header className="flex flex-wrap items-end justify-between gap-4"> <div className="min-w-0"> <h3 className="text-sm font-medium text-muted-foreground">{title}</h3> {description && <p className="mt-0.5 text-xs text-muted-foreground/80">{description}</p>} </div> <div className="text-right" aria-hidden> <div className="text-xs text-muted-foreground">{caption}</div> <div className="text-2xl font-semibold tracking-tight tabular-nums">{valueFormatter(headline ?? 0)}</div> </div> </header> <ChartContainer config={config} title={label} className="mt-4 aspect-auto h-56 w-full"> <RechartsBarChart data={data} margin={{ left: 4, right: 4, top: 12, bottom: 0 }} onMouseMove={(state) => { const i = Number(state.activeTooltipIndex); setHovered(Number.isFinite(i) && state.isTooltipActive ? i : null); }} onMouseLeave={() => setHovered(null)} > <CartesianGrid vertical={false} /> <XAxis dataKey={index} tickLine={false} axisLine={false} tickMargin={8} /> <ChartTooltip cursor={false} isAnimationActive={!reduceMotion} content={<ChartTooltipContent hideIndicator={false} indicator="dot" />} /> <Bar dataKey={dataKey} name={typeof seriesLabel === "string" ? seriesLabel : dataKey} fill={`var(--color-${dataKey})`} shape={renderBar} activeBar={renderBar} isAnimationActive={!reduceMotion} animationDuration={800} animationEasing="ease-out" /> </RechartsBarChart> </ChartContainer> <table className="sr-only"> <caption>{label}</caption> <thead> <tr> <th scope="col">{index}</th> <th scope="col">{typeof seriesLabel === "string" ? seriesLabel : dataKey}</th> </tr> </thead> <tbody> {data.map((d, i) => ( <tr key={i}> <th scope="row">{String(d[index])}</th> <td>{valueFormatter(values[i] ?? 0)}</td> </tr> ))} </tbody> </table> </section> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| title / description | ReactNode | — | Card heading. A string title also names the chart. |
| data / config | Record<string, string | number>[] / ChartConfig | — | Rows and the config entry for `dataKey`. |
| index / dataKey | string | — | Category key and value key. |
| summary | "total" | "average" | "last" | "total" | Headline when nothing is hovered. |
| valueFormatter | (value: number) => string | — | Formats the headline, tooltip and table. |
| chartLabel | string | — | Accessible name when the title isn't a string. |
Radial Stat
A rounded ring sweeps to the value while the number in the middle counts up with it (a Motion value, so the count never re-renders React). The figure is labelled with the exact value and percentage; the moving counter is hidden from screen readers.
import { RadialStat } from "@/components/dusk/chart/radial-stat";
export default function RadialStatDemo() {
return (
<div className="grid w-full max-w-xl grid-cols-1 justify-items-center gap-8 sm:grid-cols-3">
<RadialStat value={72} max={100} label="Storage" unit="GB" />
<RadialStat value={8_420} max={10_000} label="API calls" color="var(--chart-3)" caption="Resets in 6 days" />
<RadialStat value={96} max={100} label="Uptime" unit="%" color="var(--chart-4)" caption="Last 30 days" />
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/radial-stat.json1. Install the dependencies.
npm install motion recharts2. Copy the source into
components/dusk/chart/radial-stat.tsx.radial-stat.tsx "use client"; import * as React from "react"; import { PolarAngleAxis, RadialBar, RadialBarChart } from "recharts"; import { animate, motion, useMotionValue, useReducedMotion, useTransform } from "motion/react"; import { ChartContainer, type ChartConfig } from "@/components/ui/chart"; import { cn } from "@/lib/utils"; export interface RadialStatProps extends Omit<React.ComponentProps<"figure">, "children"> { /** Current value. */ value: number; /** Value that fills the ring. */ max?: number; /** What is measured, e.g. "Storage". Used in the accessible name. */ label: string; /** Unit after the number, e.g. "GB". */ unit?: string; /** Ring color. Any CSS color; defaults to the primary mint. */ color?: string; /** Formats the center number. Defaults to en-US grouping. */ valueFormatter?: (value: number) => string; /** Small line under the ring. Defaults to "value of max unit". */ caption?: React.ReactNode; /** Ring thickness as a fraction of the radius (0–1). */ thickness?: number; } const numberFormat = new Intl.NumberFormat("en-US"); const defaultValueFormatter = (value: number) => numberFormat.format(value); /** * A radial progress stat: a rounded ring sweeps to the value while the * number in the middle counts up to match. The figure is labelled with the * exact value ("Storage: 72 of 100 GB, 72%"), and the counter is hidden from * screen readers so it isn't read mid-count. Under reduced motion the ring * and number appear at their final values. */ export function RadialStat({ value, max = 100, label, unit, color = "var(--color-primary)", valueFormatter = defaultValueFormatter, caption, thickness = 0.14, className, ...props }: RadialStatProps) { const reduceMotion = useReducedMotion() ?? false; const clamped = Math.min(Math.max(value, 0), max); const percent = max > 0 ? Math.round((clamped / max) * 100) : 0; const count = useMotionValue(0); const text = useTransform(count, (v) => valueFormatter(Math.round(v))); React.useEffect(() => { if (reduceMotion) { count.set(clamped); return; } const controls = animate(count, clamped, { duration: 1.1, ease: [0.16, 1, 0.3, 1] }); return () => controls.stop(); }, [clamped, count, reduceMotion]); const config = { value: { label, color } } satisfies ChartConfig; const data = [{ name: label, value: clamped, fill: "var(--color-value)" }]; const unitText = unit ? ` ${unit}` : ""; const name = `${label}: ${valueFormatter(clamped)} of ${valueFormatter(max)}${unitText}, ${percent}%`; return ( <figure className={cn("flex w-full max-w-56 flex-col items-center gap-2", className)} aria-label={name} {...props}> <div className="relative aspect-square w-full"> <ChartContainer config={config} className="aspect-square h-full w-full" aria-hidden> <RadialBarChart data={data} startAngle={90} endAngle={-270} innerRadius={`${Math.round((1 - thickness) * 100)}%`} outerRadius="100%" accessibilityLayer={false} > <PolarAngleAxis type="number" domain={[0, max]} tick={false} axisLine={false} /> <RadialBar dataKey="value" background cornerRadius={999} isAnimationActive={!reduceMotion} animationDuration={1100} animationEasing="ease-out" /> </RadialBarChart> </ChartContainer> <div aria-hidden className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center"> <span className="flex items-baseline gap-1"> <motion.span className="text-3xl font-semibold tracking-tight tabular-nums">{text}</motion.span> {unit && <span className="text-sm text-muted-foreground">{unit}</span>} </span> <span className="text-xs text-muted-foreground">{label}</span> </div> </div> <figcaption className="text-xs text-muted-foreground tabular-nums"> {caption ?? `${valueFormatter(clamped)} of ${valueFormatter(max)}${unitText} · ${percent}%`} </figcaption> </figure> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| value / max | number | — / 100 | Current value and the value that fills the ring. |
| label | string | — | What is measured; used in the accessible name. |
| unit | string | — | Shown after the number. |
| color | string | "var(--color-primary)" | Ring color, any CSS color. |
| thickness | number | 0.14 | Ring thickness as a fraction of the radius. |
| caption / valueFormatter | ReactNode / (value: number) => string | — | Line under the ring and number formatting. |
API Reference
Same parts as shadcn/ui: ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle and the ChartConfig type, plus useChart and useChartReducedMotion.
| Prop | Type | Default | Description |
|---|---|---|---|
| config | ChartConfig | — | On ChartContainer: { [key]: { label?, icon?, color? | theme? } }. |
| title | string | — | On ChartContainer: accessible name; renders the container as role="figure". |
| indicator | "dot" | "line" | "dashed" | "dot" | On ChartTooltipContent: swatch style. |
| hideLabel / hideIndicator | boolean | false | On ChartTooltipContent. |
| labelKey / nameKey | string | — | On ChartTooltipContent / ChartLegendContent: config lookup keys. |
| labelFormatter / formatter | function | — | On ChartTooltipContent: custom heading and rows. |
| hideIcon | boolean | false | On ChartLegendContent. |
Accessibility
- ChartContainer takes a title that becomes the chart's accessible name (role="figure").
- Recharts v3's accessibility layer is on: focus a chart and use the arrow keys to move the tooltip between points.
- The blocks render a visually hidden data table, so screen readers get every value without hovering.
- Under prefers-reduced-motion the blocks pass isAnimationActive={false}: series appear at their final shape and counters jump to the value.