Bar chart
One metric as vertical bars, one bar per category or period. Use it to compare amounts: orders per day, requests per endpoint. For a continuous trend, use the area chart; for a trend with no axes, use the sparkline.
Install
npx shadcn@latest add https://thrumui.dev/r/bar-chart.jsonAdds components/ui/bar-chart.tsx and installs motion. Nothing else in your project changes.
import { BarChart } from "@/components/ui/bar-chart";Data shape
type BarChartPoint = {
label: string; // axis name
value: number | null; // null = empty slot
};[
{ label: "Mon", value: 120 },
{ label: "Tue", value: 180 },
{ label: "Wed", value: null },
{ label: "Thu", value: -40 },
]Props
| Prop | Type | Default | Description |
|---|---|---|---|
data | readonly BarChartPoint[] | Required | Bars in order, left to right. |
label | string | Required | What the chart measures. Read by screen readers and used as the table caption. |
color | string | Default var(--chart-1) | Any CSS colour for the bars. |
format | Intl.NumberFormatOptions | Default compact | How values are written on the axis, in the readout and in the data table. |
locale | string | Default "en-US" | Locale for number formatting. Fixed by default so the server and the browser print the same text. |
yAxis | boolean | Default true | Show value lines and their labels. |
xAxis | boolean | Default true | Show bar labels along the bottom. When they do not all fit, every second, third or nth label is shown. |
onActiveChange | (index: number | null) => void | – | Called with the index of the bar under the cursor, or null when the cursor leaves. Use it to sync another chart or a table row. |
sound | boolean | Default true | Play a tick as the cursor moves between bars, if the visitor has sound on. |
emptyLabel | string | Default "No data" | Text shown when there is nothing to draw. |
className | string | – | Sets the size. The default is full width and 256 pixels tall. |
Motion and sound
Motion
- First draw: each bar grows from the zero line in 250 ms. Bars start 40 ms apart, and the whole entrance takes 550 ms at most however many bars there are.
- New data with the same number of bars: each bar moves to its new height in 400 ms with no overshoot, also across the zero line. A different number of bars switches at once.
- The cursor band and the readout follow the pointer on a stiff spring.
- Reduced motion: the chart appears complete, and data changes and the cursor move instantly.
Sound
- A soft tick each time the cursor lands on a different bar, at most one every 40 ms.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The chart is one tab stop. It is exposed as a slider whose value text is the bar under the cursor, for example “Tue: 180”.
- A visually hidden table carries every bar, with the label as its caption.
- The whole plot is the pointer target, so a short bar is as easy to read as a tall one.
- The cursor is a band behind the active bar. No bar is dimmed, so every bar keeps its contrast against the background.
| Keys | Action |
|---|---|
| Tab | Focus the chart. The cursor goes to the last bar. |
| ← → | Move the cursor one bar. |
| Home / End | Jump to the first or last bar. |
| Esc | Hide the cursor. |
Source
"use client";
import { useEffect, useState, type PointerEvent } from "react";
import { motion } from "motion/react";
import { cn } from "@/lib/utils";
import { formatValue, GRID_STROKE, niceDomain, niceTicks, scaleLinear, seriesColor, useChartCursor, useMarkRadius, useSize } from "@/lib/thrum-chart";
import { ENTER, FAST, INSTANT, SPRING, staggerDelay, useReducedMotion } from "@/lib/thrum-motion";
import { play } from "@/lib/thrum-sound";
export type BarChartPoint = {
/** Name of the bar on the horizontal axis. Example: "Mon" or "Checkout". */
label: string;
/** The value. `null` leaves an empty slot. */
value: number | null;
};
export type BarChartProps = {
/** Bars in order, left to right. */
data: readonly BarChartPoint[];
/** What the chart measures. Read by screen readers and used as the table caption. Example: "Orders". */
label: string;
/** Any CSS colour. Defaults to the theme's first chart colour. */
color?: string;
/** How values are written on the axis, in the readout and in the data table. */
format?: Intl.NumberFormatOptions;
locale?: string;
/** Show value lines and labels. */
yAxis?: boolean;
/** Show bar labels along the bottom. */
xAxis?: boolean;
/** Called with the index of the bar under the cursor, or `null` when the cursor leaves. */
onActiveChange?: (index: number | null) => void;
/** Play a soft tick as the cursor moves between bars, if the visitor has sound on. */
sound?: boolean;
/** Text shown when there is nothing to draw. */
emptyLabel?: string;
/** Size it with classes. The default is full width and 256 pixels tall. */
className?: string;
};
const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
const r = (n: number) => Math.round(n * 100) / 100;
// Space around the plot, in pixels. The left gutter grows with the longest axis label.
const TOP = 8;
const RIGHT = 8;
const AXIS_X = 24;
const CHAR = 7;
// Bars: a 2px gap between neighbours, 2px corners at the data end, and a width limit so two bars do not become two slabs.
const GAP = 2;
const RADIUS = 2;
const MAX_BAR = 64;
/**
* A bar from the baseline `y0` to the value at `y1`, rounded at the value end only.
* Every bar has the same commands, so one bar morphs into another, also across the baseline.
*/
function barPath(x: number, width: number, y0: number, y1: number, round: number): string {
const radius = Math.min(round, width / 2, Math.abs(y1 - y0));
const inward = y1 <= y0 ? radius : -radius;
const x1 = x + width;
return `M${r(x)},${r(y0)}V${r(y1 + inward)}Q${r(x)},${r(y1)} ${r(x + radius)},${r(y1)}H${r(x1 - radius)}Q${r(x1)},${r(y1)} ${r(x1)},${r(y1 + inward)}V${r(y0)}Z`;
}
/**
* One series as vertical bars, with value lines, a reading cursor and a readout.
* Bars always start at zero, so their lengths can be compared. Negative values hang below the baseline.
* Move the pointer over it, or focus it and use the arrow keys.
*/
export function BarChart({
data,
label,
color,
format,
locale,
yAxis = true,
xAxis = true,
onActiveChange,
sound = true,
emptyLabel = "No data",
className,
}: BarChartProps) {
const reduced = useReducedMotion();
const [ref, { width, height }] = useSize<HTMLDivElement>();
const round = useMarkRadius(RADIUS);
const { active, move, cursorProps } = useChartCursor(data.length, onActiveChange);
// The staggered entrance runs once. After it, bars move on the data spring and new bars appear in place.
const [entered, setEntered] = useState(false);
const fill = color ?? seriesColor(0);
const say = (v: number | null | undefined) => formatValue(v, format, locale);
useEffect(() => {
if (sound && active !== null) play("tick");
}, [active, sound]);
const count = data.length;
const finite = data.map((d) => d.value).filter(isNum);
const hasData = finite.length > 0;
const lo = Math.min(0, ...finite);
const hi = Math.max(0, ...finite);
const [y0, y1] = lo === hi ? [0, 1] : niceDomain(lo, hi, 4);
const ticks = niceTicks(y0, y1, 4);
const left = yAxis ? Math.max(...ticks.map((t) => say(t).length), 1) * CHAR + 12 : RIGHT;
const bottom = xAxis ? AXIS_X : TOP;
const plotW = Math.max(0, width - left - RIGHT);
const plotH = Math.max(0, height - TOP - bottom);
const measured = plotW > 0 && plotH > 0;
const y = scaleLinear([y0, y1], [TOP + plotH, TOP]);
// Each bar owns an equal slot. The gap closes when slots get too thin to afford it.
const slot = count ? plotW / count : 0;
const gap = slot >= 6 ? GAP : slot >= 3 ? 1 : 0;
const barW = Math.min(MAX_BAR, slot - gap);
const centre = (i: number) => left + slot * (i + 0.5);
const flat = (i: number) => barPath(centre(i) - barW / 2, barW, y(0), y(0), round);
// Bottom labels: every nth one, leaving comfortable breathing room so dates never crowd shoulder-to-shoulder.
const widest = Math.max(0, ...data.map((d) => d.label.length)) * CHAR + 20;
const step = Math.max(1, Math.ceil(widest / Math.max(slot, 1)), count >= 10 && slot < 68 ? 2 : 1);
const activeX = active !== null ? centre(active) : 0;
const halo = Math.min(slot, barW + 12);
const reading = active !== null && data[active] ? `${data[active].label}: ${say(data[active].value)}` : "";
const follow = reduced ? INSTANT : SPRING.follow;
const onPointer = (event: PointerEvent<SVGRectElement>) => {
const box = event.currentTarget.ownerSVGElement?.getBoundingClientRect();
if (box && slot > 0) move(Math.floor((event.clientX - box.left - left) / slot));
};
return (
<div ref={ref} data-slot="bar-chart" className={cn("relative h-64 w-full text-xs tabular-nums", className)}>
{measured && hasData && (
<svg
width={width}
height={height}
className="absolute inset-0 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
{...cursorProps(`${label}. Use the arrow keys to read values.`, reading || `${count} bars`)}
>
{yAxis &&
ticks.map((t) => (
<g key={t} aria-hidden="true">
<line
x1={left}
x2={left + plotW}
y1={y(t)}
y2={y(t)}
stroke={t === 0 ? "color-mix(in srgb, var(--foreground) 24%, transparent)" : GRID_STROKE}
strokeWidth={1}
strokeDasharray={t === 0 ? undefined : "2 4"}
/>
<text x={left - 8} y={y(t)} dy="0.32em" textAnchor="end" fill="color-mix(in srgb, var(--foreground) 78%, transparent)">
{say(t)}
</text>
</g>
))}
{xAxis &&
data.map((d, i) => {
if (i % step !== 0) return null;
// Centred under its bar, but pulled in at the edges so it is never cut off.
const half = (d.label.length * CHAR) / 2;
return (
<text key={i} aria-hidden="true" x={Math.max(half, Math.min(width - half, centre(i)))} y={height - 6} textAnchor="middle" fill="color-mix(in srgb, var(--foreground) 78%, transparent)">
{d.label}
</text>
);
})}
{/* The cursor is a band behind the bar. Every bar keeps its full colour, so none loses contrast. */}
{active !== null && (
<motion.rect
aria-hidden="true"
y={TOP}
width={halo}
height={plotH}
rx={round}
fill="var(--foreground)"
fillOpacity={0.1}
initial={{ x: activeX - halo / 2 }}
animate={{ x: activeX - halo / 2 }}
transition={follow}
/>
)}
{/* A different number of bars is a different chart: it is drawn again at once, not morphed. */}
<g key={count} aria-hidden="true">
{data.map((d, i) => {
const d1 = barPath(centre(i) - barW / 2, barW, y(0), isNum(d.value) ? y(d.value) : y(0), round);
return (
<motion.path
key={i}
d={d1}
fill={fill}
initial={reduced || entered ? false : { d: flat(i) }}
animate={{ d: d1 }}
transition={reduced ? INSTANT : entered ? SPRING.data : { ...ENTER, delay: staggerDelay(i, count) }}
// The first bar to land ends the entrance. Bars still waiting for their turn keep their delay.
onAnimationComplete={() => setEntered(true)}
/>
);
})}
</g>
{/* The whole plot is the hit area, so a short bar is as easy to read as a tall one. */}
<rect
x={left}
y={TOP}
width={plotW}
height={plotH}
fill="transparent"
style={{ touchAction: "pan-y" }}
onPointerMove={onPointer}
onPointerDown={onPointer}
onPointerLeave={() => move(null)}
/>
</svg>
)}
{measured && hasData && active !== null && data[active] && (
<motion.div
aria-hidden="true"
data-surface="floating"
className="pointer-events-none absolute top-0 left-0 z-10 rounded-md border bg-popover px-2 py-1 whitespace-nowrap text-popover-foreground shadow-md"
initial={{ opacity: 0, x: activeX, y: TOP }}
animate={{ opacity: 1, x: activeX, y: TOP }}
transition={reduced ? INSTANT : { ...follow, opacity: FAST }}
// Sit beside the bar: to its right, or to its left in the right-hand half.
style={{ translate: activeX > left + plotW / 2 ? `calc(-100% - ${r(halo / 2 + 6)}px)` : `${r(halo / 2 + 6)}px` }}
>
<span className="text-muted-foreground">{data[active].label}</span>
<span className="ml-2 font-medium">{say(data[active].value)}</span>
</motion.div>
)}
{!hasData && <p className="absolute inset-0 grid place-items-center text-sm text-muted-foreground">{emptyLabel}</p>}
<div className="sr-only">
<table>
<caption>{label}</caption>
<tbody>
{data.map((d, i) => (
<tr key={i}>
<th scope="row">{d.label}</th>
<td>{say(d.value)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}Files and dependencies
- Adds
components/ui/bar-chart.tsx- Packages
motion- Brings along
- Chart foundationsMotion tokensSound engine
Changelog
- 1.0.1 · 2026-12-03Corners follow the project's --radius, down to square.
- 1.0.0 · 2026-12-02First release.