When to use
- The trend beside a headline number: signups, revenue, active users over the last 30 days.
- A column of small trends in a list or table row, one per metric.
- A compact chart people can scrub to read a single day's value (
interactive).
When not to use
- When people need axes, gridlines or several series to compare: use Area Chart.
- A single value against a goal: use Progress.
Installation
pnpm dlx shadcn add https://eased.dev/r/sparkline.jsonnpx shadcn add https://eased.dev/r/sparkline.jsonyarn dlx shadcn add https://eased.dev/r/sparkline.jsonbunx --bun shadcn add https://eased.dev/r/sparkline.jsonThe command adds Sparkline, everything it builds on and Eased’s tokens to your project.
Add the Eased pieces it builds on
Copy each item’s files the same way, or install them with the CLI:
Copy the source into your project
components/eased/sparkline/sparkline.tsxTSX "use client";import { animate, motion, useMotionValue, useTransform } from "motion/react";import { useCallback, useId, useLayoutEffect, useMemo, useRef } from "react";import { snappy, useSafeReducedMotion } from "../lib/motion";import { useDrawIn } from "../_primitives/chart-core/draw-in";import { samplesToArea, samplesToPath, useMorphPath, type Curve, type MorphFrame } from "../_primitives/chart-core/morph";import { linear, type Domain } from "../_primitives/chart-core/scales";import { ChartTooltip, Crosshair, useActiveStore, useChartScrub } from "../_primitives/chart-core/scrub";import { useChartTransition } from "../_primitives/chart-core/range";import { useChartSize } from "../_primitives/chart-core/use-chart-size";import { ChartTokens, chartColor } from "../_primitives/chart-core/tokens";export type SparklineProps = { /** The values, oldest first, evenly spaced. */ values: readonly number[]; /** Accessible name, e.g. "Revenue, last 30 days". A summary (first, last, low, high) is appended. */ label: string; /** Stroke colour. Default `var(--eased-chart-1)`. Use `chartColor(n)` or any token. */ color?: string; /** Height in px. Default 32. The width follows the container. */ height?: number; /** Add a soft wash under the line. Default false. */ area?: boolean; /** Mark the newest value with a dot ringed in the surface colour. Default true. */ dot?: boolean; /** Default "monotone". */ curve?: Curve; /** Include zero in the value range (honest for counts and money). Default false: a sparkline shows shape. */ zero?: boolean; /** Scrub to read values: a crosshair and a small readout, and the sparkline becomes a slider. Default false. */ interactive?: boolean; /** Formats values for the readout and screen readers. */ format?: (value: number) => string; /** The label of point `i` for the readout and screen readers, e.g. its date. */ formatIndex?: (index: number) => string; onActiveChange?: (index: number | null) => void; className?: string;};const PAD = 5; // dot radius + ring: the newest point never clipsconst fallbackFormat = (v: number) => new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(v);function extent(values: readonly number[], zero: boolean): Domain { let lo = Infinity; let hi = -Infinity; for (const v of values) { if (v < lo) lo = v; if (v > hi) hi = v; } if (lo === Infinity) return [0, 1]; if (zero) [lo, hi] = [Math.min(0, lo), Math.max(0, hi)]; if (lo === hi) return [lo - 1, hi + 1]; return [lo, hi];}/** * A word-sized line chart. It draws in left to right the first time it scrolls into view, * then the newest point settles in as a dot ringed in the surface colour. New values morph * the line from the shape on screen, so it can sit in a Stat Tile that changes range. */export function Sparkline({ values, label, color = chartColor(1), height = 32, area = false, dot = true, curve = "monotone", zero = false, interactive = false, format = fallbackFormat, formatIndex, onActiveChange, className = "",}: SparklineProps) { const reduced = useSafeReducedMotion(); const transition = useChartTransition(); const [box, { width }] = useChartSize(); const id = useId().replace(/:/g, ""); const line = useRef<SVGPathElement>(null); const fill = useRef<SVGPathElement>(null); const end = useRef<SVGCircleElement>(null); const progress = useDrawIn(box, { reduced }); const widthMV = useMotionValue(width); useLayoutEffect(() => widthMV.set(width), [width, widthMV]); const clipWidth = useTransform([progress, widthMV], ([p, w]: number[]) => p * (w + PAD * 2)); const dotOpacity = useTransform(progress, [0.88, 1], [0, 1]); const dotScale = useTransform(progress, [0.88, 1], [0.5, 1]); const domain = useMemo(() => extent(values, zero), [values, zero]); const plotW = Math.max(0, width - PAD); const draw = useCallback( (f: MorphFrame) => { const s = f.series.v; if (!s) return; const x = (u: number) => u * plotW; const y = linear(f.domain, [height - PAD, PAD]); line.current?.setAttribute("d", samplesToPath(s, x, y)); fill.current?.setAttribute("d", samplesToArea(s, x, y, height)); if (end.current) { end.current.setAttribute("cx", String(x(1))); end.current.setAttribute("cy", String(y(s[s.length - 1]))); } }, [plotW, height], ); const morph = useMorphPath( { series: { v: values }, domain }, { onFrame: draw, curve, transition, animate: !reduced, samples: Math.min(240, Math.max(64, values.length * 12)) }, ); useLayoutEffect(() => morph.redraw(), [draw, morph]); // Scrubbing (opt-in). const store = useActiveStore(); const n = values.length; const xOf = useCallback((i: number) => (n > 1 ? (i / (n - 1)) * plotW : plotW), [n, plotW]); const indexAt = useCallback((px: number) => (n > 1 ? Math.round((px / Math.max(1, plotW)) * (n - 1)) : 0), [n, plotW]); const valueText = useCallback((i: number) => `${formatIndex ? `${formatIndex(i)}: ` : ""}${format(values[i] ?? 0)}`, [format, formatIndex, values]); const activeY = useMotionValue(0); const scrub = useChartScrub({ count: n, store, xOf, indexAt, valueText, label, reduced, onActiveChange: (i) => { if (i !== null) { const y = linear(domain, [height - PAD, PAD])(values[i]); if (reduced || scrub.opacity.get() < 0.01) activeY.jump(y); else animate(activeY, y, snappy); } onActiveChange?.(i); }, }); const summary = n ? `${format(values[0])} to ${format(values[n - 1])}, low ${format(Math.min(...values))}, high ${format(Math.max(...values))}` : "no data"; return ( <div ref={box} className={`relative w-full min-w-0 ${className}`} style={{ height }} {...(interactive ? {} : { role: "img", "aria-label": `${label}: ${summary}` })} > <ChartTokens /> {width > 0 && ( <svg aria-hidden width={width} height={height} className="absolute inset-0 overflow-visible"> <defs> <clipPath id={`${id}-clip`}> <motion.rect x={-PAD} y={-PAD} height={height + PAD * 2} width={clipWidth} /> </clipPath> <linearGradient id={`${id}-wash`} x1="0" y1="0" x2="0" y2="1"> <stop offset="0" stopColor={color} stopOpacity={0.18} /> <stop offset="1" stopColor={color} stopOpacity={0} /> </linearGradient> </defs> <g clipPath={`url(#${id}-clip)`}> {area && <path ref={fill} fill={`url(#${id}-wash)`} />} <path ref={line} fill="none" stroke={color} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" /> </g> {interactive && ( <> <Crosshair x={scrub.x} opacity={scrub.opacity} height={height} /> <motion.circle r={3} cx={0} fill={color} stroke="var(--chart-surface, var(--eased-surface))" strokeWidth={2} paintOrder="stroke" style={{ x: scrub.x, y: activeY, opacity: scrub.opacity }} /> </> )} {dot && n > 0 && ( <motion.circle ref={end} r={3} fill={color} stroke="var(--chart-surface, var(--eased-surface))" strokeWidth={2} paintOrder="stroke" style={{ opacity: dotOpacity, scale: dotScale, transformBox: "fill-box", transformOrigin: "center" }} /> )} </svg> )} {interactive && ( <> <div {...scrub.props} className="absolute inset-0 cursor-crosshair rounded-control-xs focus-ring" /> <ChartTooltip store={store} xOf={xOf} width={width} top={-38} reduced={reduced} className="whitespace-nowrap py-1.5"> {(i) => ( <span className="flex items-baseline gap-2"> {formatIndex && <span className="text-text-muted">{formatIndex(i)}</span>} <span className="font-medium tabular-nums">{format(values[i] ?? 0)}</span> </span> )} </ChartTooltip> </> )} </div> );}Keep the folder layout
The files import each other by relative path (
../lib/motion), so keep each one at the path shown, undercomponents/eased/.
Usage
import { Sparkline } from "@/components/eased/sparkline/sparkline";export function SignupsTrend({ signups }: { signups: number[] }) { return <Sparkline values={signups} label="Signups, last 30 days" />;}Examples
Scrubbable with a wash
interactive adds a crosshair and a small readout; formatIndex labels each point, usually with its date.
const int = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });<Sparkline values={visitors} label="Daily active users, last 30 days" height={56} area interactive format={(v) => int.format(v)} formatIndex={(i) => dates[i]}/>Colour by health
Any colour token works. chartColor(n) gives the nth chart colour.
import { chartColor } from "@/components/eased/_primitives/chart-core/tokens";<Sparkline values={latency} label="p95 latency" height={20} color={healthy ? chartColor(1) : "var(--eased-warning)"} />API reference
Sparkline
| Prop | Type | Default | Description |
|---|---|---|---|
values | readonly number[] | Oldest first, evenly spaced. | |
label | string | Accessible name; a first, last, low and high summary is appended. | |
color | string | var(--eased-chart-1) | Any colour token, or chartColor(n). |
height | number | 32 | Pixels. The width follows the container. |
area | boolean | false | A soft wash under the line. |
dot | boolean | true | Marks the newest point, ringed in the surface colour. Set --chart-surface when it sits on a different background. |
curve | "monotone" | "linear" | "monotone" | |
zero | boolean | false | Include zero in the range, for counts and money. Off, the line uses the full height to show shape. |
interactive | boolean | false | Scrub for a readout; the sparkline becomes a keyboard slider. |
format | (value: number) => string | up to one decimal | Formats values for the readout and screen readers. |
formatIndex | (index: number) => string | The label of point i, e.g. its date. | |
onActiveChange | (index: number | null) => void | The scrubbed point, or null when scrubbing ends. | |
className | string | "" |
Keyboard
With interactive:
| Key | Action |
|---|---|
Tab | Focuses the sparkline on its newest point. |
← / → | Moves one point back or forward (↓ / ↑ too). |
Page Down / Page Up | Moves a tenth of the points. |
Home / End | First or last point. |
Escape | Hides the readout. |
Accessibility
- Static, it is
role="img"named "Signups, last 30 days: 120 to 184, low 96, high 201", usingformat. - Interactive, it is a
role="slider"whosearia-valuetextreads the point's label and value, e.g. "Oct 18: 2,410". - Touch scrubbing leaves vertical page scroll alone.
Motion
It draws in left to right over 0.9s the first time a third of it scrolls into view, and the newest point fades and scales in as a ringed dot at the end of the draw. New values morph the line from the shape on screen on the smooth spring instead of redrawing it, so a range switch reads as one change. While scrubbing, the crosshair glides between points and the marker follows on the snappy spring. Reduced motion: the line is drawn at once and new values replace it without morphing.
Notes for AI
Give Sparkline a container with a width, a label that names the metric and period, and a format that matches the number beside it. Keep zero off for trends and turn it on when the absolute size matters. Use interactive only where there is room for the readout above it.
Do not add axes, gridlines or a tooltip of your own, and do not re-key it to replay the draw on new data: changing values morphs it from the current shape.
Related components
- Animated Area Chart: a full chart with axes and a crosshair.
- Animated Number Counter: the rolling value that usually sits beside it.
- Animated Bar Chart