KPI statFree
One number with its change in words, an optional target meter and sparkline. Plain SVG: no chart engine.
npx shadcn@latest add https://beautifulcharts.dev/r/kpi-stat.jsonUsage
A complete client module. Install the item first, then paste it into your app.
"use client";
import { KpiStat } from "@/components/beautiful-charts/themes/instrument/kpi-stat";
// A change from a zero base is shown as an amount, never as an infinite percentage.
export function ActiveTeams() {
return (
<KpiStat
title="Active teams"
value={74}
previous={38}
previousLabel="last week"
target={80}
trend={[38, 42, 40, 47, 51, null, 55, 61, 63, 64, 69, 74]}
unit="teams with a weekly session"
/>
);
}
Props
value*
number | null
The number. null or undefined shows the empty state.
previous
number | null
The comparison value, e.g. last period.
previousLabel
string
What the comparison is, e.g. "last month".
target
number | null
A goal. Adds a meter showing progress toward it.
trend
(number | null)[]
Recent values, oldest first, for the sparkline. Missing values break the line.
polarity
"up" | "down"
"up" when a rise is good (default), "down" for costs, churn, latency.
| Prop | Type | Description |
|---|---|---|
| value* | number | null | The number. null or undefined shows the empty state. |
| previous | number | null | The comparison value, e.g. last period. |
| previousLabel | string | What the comparison is, e.g. "last month". |
| target | number | null | A goal. Adds a meter showing progress toward it. |
| trend | (number | null)[] | Recent values, oldest first, for the sparkline. Missing values break the line. |
| polarity | "up" | "down" | "up" when a rise is good (default), "down" for costs, churn, latency. |
Sourcecomponents/beautiful-charts/themes/instrument/kpi-stat.tsx
Show the source (107 lines)
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import type { Density } from "../../core/contracts";
import { useKpiModel, type KpiProps } from "../../core/kpi";
import { linePath, type Point } from "../../core/plot";
import { ChartState, Odometer } from "../../core/chart";
import { chartState } from "../../core/state";
import { InstrumentFrame } from "./frame";
export type KpiStatProps = KpiProps & {
/** Small label above the title. */
eyebrow?: ReactNode | undefined;
/** A line or action at the bottom of the card. */
footer?: ReactNode | undefined;
/** Card title. A string also names the stat for screen readers. */
title?: ReactNode | undefined;
/** A line under the title. */
description?: ReactNode | undefined;
/** Small unit or context under the number, e.g. "active teams". */
unit?: ReactNode | undefined;
/** Show the loading state. */
loading?: boolean | undefined;
/** An error message; shows the error state. */
error?: string | null | undefined;
/** "comfortable" (default) or "compact". */
density?: Density | undefined;
/** Classes on the card. */
className?: string | undefined;
/** "theme" (default) or "shadcn" to use your --chart-N colours. */
palette?: "theme" | "shadcn" | undefined;
/** Sparkline height in px. */
trendHeight?: number | undefined;
};
/** Sample props used when you install the stat; replace them with your own. */
export const kpiStatSample = { value: 74, previous: 38, previousLabel: "W27", trend: [38, 42, 40, 47, 51, null, 55, 61, 63, 64, 69, 74], target: 80 };
/**
* KPI stat, Instrument theme. Plain SVG: it pulls in neither Recharts nor ECharts.
* One number rolls in like an odometer; the change is said in words and tinted by meaning; an optional
* target meter and sparkline add context. It's read-only, so it takes no tab stop: screen readers get one
* summary sentence.
*/
export function KpiStat(props: KpiStatProps) {
const m = useKpiModel(props);
const state = chartState({ loading: props.loading, error: props.error, hasData: m.value !== null || m.trend.some((v) => v !== null) });
const summary = m.summary;
return (
<InstrumentFrame palette={props.palette} state={state} series={[]} density={props.density} className={props.className} label={typeof props.title === "string" ? `${props.title}. ${summary}` : summary}
eyebrow={props.eyebrow} title={props.title} description={props.description} footer={props.footer} legend={false} legendItems={[]} onToggle={() => {}} table={false}
error={props.error} k={m.k}
emptyState={<ChartState state="empty" message="No value yet."><span data-slot="kpi-empty" aria-hidden="true">—</span></ChartState>}>
<div data-slot="kpi" role="group" aria-label={summary}>
<div data-slot="kpi-row" aria-hidden="true">
<div data-slot="readout-value" data-size="kpi"><Odometer value={m.format(m.value)} /></div>
{m.delta ? <div data-slot="kpi-delta"><span data-slot="readout-delta" data-tone={m.delta.tone}>{m.delta.arrow} {m.delta.text}</span><span data-slot="kpi-context">{m.delta.context}</span></div> : null}
</div>
{props.unit ? <div data-slot="readout-unit" aria-hidden="true">{props.unit}</div> : null}
{m.progress !== null ? <TargetMeter progress={m.progress} label={`${m.f.percent(m.progress, 0)} of ${m.format(m.target)}`} /> : null}
{m.trend.length > 1 ? <Sparkline values={m.trend} height={props.trendHeight ?? 56} /> : null}
<p data-slot="sr-only">{summary}</p>
</div>
</InstrumentFrame>
);
}
function TargetMeter({ progress, label }: { progress: number; label: string }) {
const shown = Math.max(0, Math.min(1, progress));
return (
<div data-slot="kpi-target" aria-hidden="true">
<div data-slot="kpi-track"><div data-slot="kpi-fill" style={{ width: `${shown * 100}%` }} />{progress > 1 ? <span data-slot="kpi-over" /> : null}</div>
<span data-slot="kpi-target-label">{label}</span>
</div>
);
}
/** A sparkline measured to its container. Gaps stay gaps; the latest point is marked. */
function Sparkline({ values, height }: { values: (number | null)[]; height: number }) {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const element = ref.current;
if (!element) return;
const observer = new ResizeObserver(([entry]) => setWidth(entry!.contentRect.width));
observer.observe(element);
return () => observer.disconnect();
}, []);
const present = values.filter((v): v is number => v !== null);
const min = Math.min(...present), max = Math.max(...present), span = max - min || 1;
const pad = 4;
const points = values.map((v, i) => (v === null ? null : ([pad + (i * (width - 2 * pad)) / Math.max(1, values.length - 1), pad + (1 - (v - min) / span) * (height - 2 * pad)] as Point)));
const lastIndex = values.map((v, i) => (v === null ? -1 : i)).filter((i) => i >= 0).at(-1) ?? -1;
const last = lastIndex >= 0 ? points[lastIndex] : null;
const line = width > 0 ? linePath(points, "monotone") : "";
return (
<div ref={ref} data-slot="kpi-trend" aria-hidden="true" style={{ height }}>
{width > 0 ? (
<svg width={width} height={height}>
<path className={"bc-draw bc-line bc-kpi-line"} d={line} fill="none" style={{ ["--len" as string]: Math.ceil(width * 1.6) }} />
{last ? <circle className={"bc-late bc-kpi-dot"} cx={last[0]} cy={last[1]} r={3} /> : null}
</svg>
) : null}
</div>
);
}
Details
The other 13 kpi stat props
valueFormatter
(value: number) => string
Formats the number, change and target.
motion
MotionPreference
"full" (default), "subtle" or "off". Reduced-motion settings always win.
eyebrow
ReactNode
Small label above the title.
footer
ReactNode
A line or action at the bottom of the card.
title
ReactNode
Card title. A string also names the stat for screen readers.
description
ReactNode
A line under the title.
unit
ReactNode
Small unit or context under the number, e.g. "active teams".
loading
boolean
Show the loading state.
error
string | null
An error message; shows the error state.
density
Density
"comfortable" (default) or "compact".
className
string
Classes on the card.
palette
"theme" | "shadcn"
"theme" (default) or "shadcn" to use your --chart-N colours.
trendHeight
number
Sparkline height in px.
| Prop | Type | Description |
|---|---|---|
| valueFormatter | (value: number) => string | Formats the number, change and target. |
| motion | MotionPreference | "full" (default), "subtle" or "off". Reduced-motion settings always win. |
| eyebrow | ReactNode | Small label above the title. |
| footer | ReactNode | A line or action at the bottom of the card. |
| title | ReactNode | Card title. A string also names the stat for screen readers. |
| description | ReactNode | A line under the title. |
| unit | ReactNode | Small unit or context under the number, e.g. "active teams". |
| loading | boolean | Show the loading state. |
| error | string | null | An error message; shows the error state. |
| density | Density | "comfortable" (default) or "compact". |
| className | string | Classes on the card. |
| palette | "theme" | "shadcn" | "theme" (default) or "shadcn" to use your --chart-N colours. |
| trendHeight | number | Sparkline height in px. |
Props every chart shares (2): locale, timeZone
locale
string
BCP 47 locale. Defaults to "en-US" so server and client render the same text.
timeZone
string
IANA time zone for dates. Defaults to "UTC" so server and client agree.
| Prop | Type | Description |
|---|---|---|
| locale | string | BCP 47 locale. Defaults to "en-US" so server and client render the same text. |
| timeZone | string | IANA time zone for dates. Defaults to "UTC" so server and client agree. |
- Pointer
- Not interactive.
- Keyboard
- Not focusable: there's nothing to move between.
- Screen readers
- A labelled group: the value, its change in words and the target are read as one sentence.
- Motion
- The value rolls in digit by digit, the trend line draws, then the change fades in. With reduced motion it appears settled at once.