Stat cards with sparklines
Dashboard KPI cards: numbers count up, sparklines draw themselves, and hovering the line shows the exact value for that day.
"use client";
import {
useEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./stat-cards.css";
type Stat = {
label: string;
value: number;
prefix?: string;
suffix?: string;
decimals?: number;
change: number;
data: number[];
unit: string;
good: "up" | "down";
};
const STATS: Stat[] = [
{
label: "Revenue",
value: 48210,
prefix: "$",
change: 12.4,
good: "up",
unit: "k",
data: [31, 34, 33, 38, 36, 41, 40, 44, 43, 47, 46, 48.2],
},
{
label: "Active users",
value: 9382,
change: 4.1,
good: "up",
unit: "k",
data: [8.1, 8.3, 8.2, 8.6, 8.5, 8.8, 8.7, 9.0, 8.9, 9.2, 9.1, 9.38],
},
{
label: "Churn",
value: 2.3,
suffix: "%",
decimals: 1,
change: -0.6,
good: "down",
unit: "%",
data: [3.4, 3.2, 3.3, 3.0, 2.9, 3.0, 2.7, 2.8, 2.6, 2.5, 2.4, 2.3],
},
];
const W = 240;
const H = 64;
/** Count from 0 to `to` with an ease-out curve when `run` turns true. */
function useCount(to: number, run: boolean) {
const [n, setN] = useState(0);
useEffect(() => {
if (!run) return;
let raf = 0;
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
const start = performance.now();
const tick = (now: number) => {
const t = reduce ? 1 : Math.min(1, (now - start) / 1400);
setN(to * (1 - Math.pow(1 - t, 4)));
if (t < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [to, run]);
return n;
}
function Card({ s, run }: { s: Stat; run: boolean }) {
const n = useCount(s.value, run);
const [hover, setHover] = useState<number | null>(null);
const min = Math.min(...s.data);
const max = Math.max(...s.data);
const pts = s.data.map(
(v, i) =>
[
(i / (s.data.length - 1)) * W,
H - 6 - ((v - min) / (max - min || 1)) * (H - 12),
] as const,
);
const line = pts
.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`)
.join(" ");
const area = `${line} L${W} ${H} L0 ${H} Z`;
const positive = s.change > 0 === (s.good === "up");
const fmt = (v: number) =>
`${s.prefix ?? ""}${v.toLocaleString("en-US", { minimumFractionDigits: s.decimals ?? 0, maximumFractionDigits: s.decimals ?? 0 })}${s.suffix ?? ""}`;
const months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
const r = e.currentTarget.getBoundingClientRect();
setHover(
Math.round(((e.clientX - r.left) / r.width) * (s.data.length - 1)),
);
};
return (
<article className="gu-stat" data-good={positive ? "" : undefined}>
<header>
<h3>{s.label}</h3>
<span className="gu-stat__chip">
{s.change > 0 ? "▲" : "▼"} {Math.abs(s.change)}%
</span>
</header>
<p className="gu-stat__value">
<span aria-hidden="true">{fmt(n)}</span>
<span className="gu-sr">
{fmt(s.value)}, {s.change > 0 ? "up" : "down"} {Math.abs(s.change)}%
from last month
</span>
</p>
<p className="gu-stat__readout" aria-hidden="true">
{hover !== null
? `${months[hover]}: ${s.prefix ?? ""}${s.data[hover]}${s.unit}`
: "Last 12 months"}
</p>
<svg
viewBox={`0 0 ${W} ${H}`}
preserveAspectRatio="none"
className="gu-stat__spark"
data-run={run ? "" : undefined}
onPointerMove={onMove}
onPointerDown={onMove}
onPointerLeave={() => setHover(null)}
aria-hidden="true"
>
<path d={area} className="gu-stat__area" />
<path d={line} className="gu-stat__line" pathLength={1} />
{hover !== null && (
<>
<line
x1={pts[hover][0]}
x2={pts[hover][0]}
y1="0"
y2={H}
className="gu-stat__guide"
/>
<circle
cx={pts[hover][0]}
cy={pts[hover][1]}
r="4"
className="gu-stat__dot"
/>
</>
)}
</svg>
</article>
);
}
/**
* StatCards
* - Starts counting when the row scrolls into view.
* - "Good" direction is per stat: churn going down is green.
*/
export function StatCards({ theme = "light" }: { theme?: "light" | "dark" }) {
const root = useRef<HTMLDivElement>(null);
const [run, setRun] = useState(false);
useEffect(() => {
const io = new IntersectionObserver(
([e]) => e.isIntersecting && setRun(true),
{ threshold: 0.3 },
);
if (root.current) io.observe(root.current);
return () => io.disconnect();
}, []);
return (
<div ref={root} className="gu-stats" data-theme={theme}>
{STATS.map((s) => (
<Card key={s.label} s={s} run={run} />
))}
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Stat cards with sparklines
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A row of three dashboard KPI cards (Revenue, Active users, Churn). On scroll-in the numbers count up and the sparklines draw themselves, then a soft area fill appears. Hover or drag along a sparkline to read the value for each month.
## Layout and look
- Three equal cards (one column under 680px), radius 22px, padding 20px; the sparkline bleeds to the card's left/right edges at the bottom.
- Header: muted label + a change chip ("▲ 12.4%") tinted green when the change is good, red when bad (churn going down is good).
- Value: clamp 29–42px, weight 900, tracking -0.045em, tabular numbers.
- Readout line: "Last 12 months" or "Aug: 44k" while hovering.
- Sparkline: 2.5px orange line (non-scaling stroke), 12% orange area, dashed vertical guide and a hollow dot at the hovered point.
## Behavior and motion
1. IntersectionObserver (30%) starts everything once.
2. Count-up: 1.4s ease-out quartic via requestAnimationFrame.
3. Line draws with pathLength=1 and dashoffset 1 → 0 (1.6s); the area fades in after 0.8s.
4. Pointer X maps to the nearest data index.
## Touch
Drag along the line (touch-action pan-y keeps vertical scrolling).
## Accessibility
- The animated number is aria-hidden; a hidden sentence gives the final value and change. Charts are decorative.
- prefers-reduced-motion: final values and lines immediately.
## Props
theme. Edit STATS.
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### StatCards.tsx
```tsx
"use client";
import {
useEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./stat-cards.css";
type Stat = {
label: string;
value: number;
prefix?: string;
suffix?: string;
decimals?: number;
change: number;
data: number[];
unit: string;
good: "up" | "down";
};
const STATS: Stat[] = [
{
label: "Revenue",
value: 48210,
prefix: "$",
change: 12.4,
good: "up",
unit: "k",
data: [31, 34, 33, 38, 36, 41, 40, 44, 43, 47, 46, 48.2],
},
{
label: "Active users",
value: 9382,
change: 4.1,
good: "up",
unit: "k",
data: [8.1, 8.3, 8.2, 8.6, 8.5, 8.8, 8.7, 9.0, 8.9, 9.2, 9.1, 9.38],
},
{
label: "Churn",
value: 2.3,
suffix: "%",
decimals: 1,
change: -0.6,
good: "down",
unit: "%",
data: [3.4, 3.2, 3.3, 3.0, 2.9, 3.0, 2.7, 2.8, 2.6, 2.5, 2.4, 2.3],
},
];
const W = 240;
const H = 64;
/** Count from 0 to `to` with an ease-out curve when `run` turns true. */
function useCount(to: number, run: boolean) {
const [n, setN] = useState(0);
useEffect(() => {
if (!run) return;
let raf = 0;
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
const start = performance.now();
const tick = (now: number) => {
const t = reduce ? 1 : Math.min(1, (now - start) / 1400);
setN(to * (1 - Math.pow(1 - t, 4)));
if (t < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [to, run]);
return n;
}
function Card({ s, run }: { s: Stat; run: boolean }) {
const n = useCount(s.value, run);
const [hover, setHover] = useState<number | null>(null);
const min = Math.min(...s.data);
const max = Math.max(...s.data);
const pts = s.data.map(
(v, i) =>
[
(i / (s.data.length - 1)) * W,
H - 6 - ((v - min) / (max - min || 1)) * (H - 12),
] as const,
);
const line = pts
.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`)
.join(" ");
const area = `${line} L${W} ${H} L0 ${H} Z`;
const positive = s.change > 0 === (s.good === "up");
const fmt = (v: number) =>
`${s.prefix ?? ""}${v.toLocaleString("en-US", { minimumFractionDigits: s.decimals ?? 0, maximumFractionDigits: s.decimals ?? 0 })}${s.suffix ?? ""}`;
const months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
const r = e.currentTarget.getBoundingClientRect();
setHover(
Math.round(((e.clientX - r.left) / r.width) * (s.data.length - 1)),
);
};
return (
<article className="gu-stat" data-good={positive ? "" : undefined}>
<header>
<h3>{s.label}</h3>
<span className="gu-stat__chip">
{s.change > 0 ? "▲" : "▼"} {Math.abs(s.change)}%
</span>
</header>
<p className="gu-stat__value">
<span aria-hidden="true">{fmt(n)}</span>
<span className="gu-sr">
{fmt(s.value)}, {s.change > 0 ? "up" : "down"} {Math.abs(s.change)}%
from last month
</span>
</p>
<p className="gu-stat__readout" aria-hidden="true">
{hover !== null
? `${months[hover]}: ${s.prefix ?? ""}${s.data[hover]}${s.unit}`
: "Last 12 months"}
</p>
<svg
viewBox={`0 0 ${W} ${H}`}
preserveAspectRatio="none"
className="gu-stat__spark"
data-run={run ? "" : undefined}
onPointerMove={onMove}
onPointerDown={onMove}
onPointerLeave={() => setHover(null)}
aria-hidden="true"
>
<path d={area} className="gu-stat__area" />
<path d={line} className="gu-stat__line" pathLength={1} />
{hover !== null && (
<>
<line
x1={pts[hover][0]}
x2={pts[hover][0]}
y1="0"
y2={H}
className="gu-stat__guide"
/>
<circle
cx={pts[hover][0]}
cy={pts[hover][1]}
r="4"
className="gu-stat__dot"
/>
</>
)}
</svg>
</article>
);
}
/**
* StatCards
* - Starts counting when the row scrolls into view.
* - "Good" direction is per stat: churn going down is green.
*/
export function StatCards({ theme = "light" }: { theme?: "light" | "dark" }) {
const root = useRef<HTMLDivElement>(null);
const [run, setRun] = useState(false);
useEffect(() => {
const io = new IntersectionObserver(
([e]) => e.isIntersecting && setRun(true),
{ threshold: 0.3 },
);
if (root.current) io.observe(root.current);
return () => io.disconnect();
}, []);
return (
<div ref={root} className="gu-stats" data-theme={theme}>
{STATS.map((s) => (
<Card key={s.label} s={s} run={run} />
))}
</div>
);
}
```
### stat-cards.css
```css
/* StatCards: change these colors to match your brand. */
.gu-stats {
--card: #fbf8f2;
--text: #0e0e10;
--muted: #57534b;
--line: rgb(14 14 16 / 0.1);
--good: #16a34a;
--bad: #dc2626;
--stroke: #ff5a1f;
container-type: inline-size;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
width: min(100%, 900px);
color: var(--text);
font-family: system-ui, sans-serif;
}
.gu-stats[data-theme="dark"] {
--card: #18181b;
--text: #f3eee3;
--muted: #aea89c;
--line: rgb(243 238 227 / 0.1);
--good: #4ade80;
--bad: #f87171;
}
.gu-stat {
display: grid;
gap: 4px;
padding: 20px 20px 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 22px;
background: var(--card);
}
.gu-stat header {
display: flex;
align-items: center;
justify-content: space-between;
}
.gu-stat h3 {
margin: 0;
color: var(--muted);
font-size: 0.9rem;
font-weight: 700;
}
.gu-stat__chip {
padding: 3px 8px;
border-radius: 999px;
background: color-mix(in srgb, var(--bad) 14%, transparent);
color: var(--bad);
font-size: 0.75rem;
font-weight: 800;
}
.gu-stat[data-good] .gu-stat__chip {
background: color-mix(in srgb, var(--good) 14%, transparent);
color: var(--good);
}
.gu-stat__value {
margin: 6px 0 0;
font-size: clamp(1.8rem, 5cqi, 2.6rem);
font-weight: 900;
letter-spacing: -0.045em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.gu-stat__readout {
min-height: 1.3em;
margin: 0;
color: var(--muted);
font-size: 0.8rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.gu-stat__spark {
display: block;
width: calc(100% + 40px);
height: 72px;
margin: 6px -20px 0;
overflow: visible;
cursor: crosshair;
touch-action: pan-y;
}
.gu-stat__line {
fill: none;
stroke: var(--stroke);
stroke-width: 2.5;
stroke-linejoin: round;
stroke-linecap: round;
vector-effect: non-scaling-stroke;
stroke-dasharray: 1;
stroke-dashoffset: 1;
}
.gu-stat__area {
fill: var(--stroke);
opacity: 0;
}
.gu-stat__spark[data-run] .gu-stat__line {
animation: gu-stat-draw 1.6s 0.1s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.gu-stat__spark[data-run] .gu-stat__area {
animation: gu-stat-area 1s 0.8s forwards;
}
@keyframes gu-stat-draw {
to {
stroke-dashoffset: 0;
}
}
@keyframes gu-stat-area {
to {
opacity: 0.12;
}
}
.gu-stat__guide {
stroke: var(--muted);
stroke-width: 1;
stroke-dasharray: 3 3;
vector-effect: non-scaling-stroke;
}
.gu-stat__dot {
fill: var(--card);
stroke: var(--stroke);
stroke-width: 2.5;
vector-effect: non-scaling-stroke;
}
.gu-sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}
@container (max-width: 680px) {
/* The root is the container, so it cannot query itself: its children span the full row instead */
.gu-stats > * {
grid-column: 1 / -1;
}
}
@media (prefers-reduced-motion: reduce) {
.gu-stat__line {
stroke-dashoffset: 0;
}
.gu-stat__area {
opacity: 0.12;
}
.gu-stat__spark[data-run] .gu-stat__line,
.gu-stat__spark[data-run] .gu-stat__area {
animation: none;
}
}
```
You might also want
Next piece: Swipe card stackActivity rings
Components, intermediate
Activity heatmap
Components, intermediate
Profile card
Components, beginner