Explore the index
Browse components
MotionstableReactIntl.NumberFormatCSS Animations

Number Drift

Only the digits that changed need to move.

Precision

Use the +/− steppers, then Randomize. Unchanged digits should stay completely still.

A real browser viewport. Scroll within the preview when the sample needs more space. Configuration stays in sync between sizes.

01What it does

An animated numeric display that aligns formatted output from the right and rolls each changed digit in the direction of the value. Separators and unchanged digits stay put, and the final value is announced once.

In this previewA printed annual-review board with four metrics. Each row has its own steppers; the header can increase or decrease everything, randomize, reset and change precision. Compact notation is available for the large values.

Design decisions

Formatted characters are aligned from the right, so growing a number does not disturb the units, decimal point or separator positions relative to the digits.

A digit rolls through the shortest directional path: 9→0 on an increase is one step, not nine. Decrease runs the strip the other way.

The number is right-aligned inside a fixed metric column. Width changes happen at the left edge, away from the unit and the reading anchor.

02Install

Registry install

registry:component

Run this in a React project with components.json. The component and its stylesheet land in components/lab/number-drift/.

npx shadcn@latest add https://lab.tanishk.me/r/number-drift.json

Files included

2
  • components/lab/number-drift/number-drift.tsxcomponent
  • components/lab/number-drift/number-drift.cssstyles

Manual install: copy each file into the same folder and preserve its relative imports. Open the source

03Usage

number-drift.usage.tsx
import { NumberDrift } from "@/components/lab/number-drift/number-drift";

export function Revenue({ value }: { value: number }) {
return (
<NumberDrift
value={value}
locale="en-GB"
prefix="£"
format={{ maximumFractionDigits: 0 }}
/>
);
}

04Props

Props accepted by Number Drift
PropTypeDefaultNotes
valuenumber—The numeric value to display.
localestring—Locale passed to Intl.NumberFormat; inherits the runtime default when omitted.
formatIntl.NumberFormatOptions—Currency, percent, compact notation, fraction digits and sign display.
prefixstring—Static text before the number, such as a currency symbol.
suffixstring—Static text after the number, such as a unit.
classNamestring—Forwarded to the inline root.

05Accessibility

  • The rolling digits are aria-hidden decoration; a visually hidden span carries the final prefix, formatted value and suffix once.
  • No live region is attached by default, so a rapidly updating metric cannot flood a screen reader.
  • Unchanged digits keep their DOM nodes, and all numeric cells use tabular figures for stable widths.
  • Reduced motion sets every roll directly to its final value with no animation.

06Source

2 files, 256 lines. The combined copy is a reference; save each file separately for use.

components/lab/number-drift/number-drift.tsx— press enter to show or hide the source
tsx
"use client";

/*
* The previous formatted string is a render-time diff snapshot. It is
* intentionally a ref: the roll needs the old and new digits in the same
* commit, and promoting it to state would render the new value once
* without animation before the snapshot could be read.
*/
/* eslint-disable react-hooks/refs */

import { useEffect, useMemo, useRef, type CSSProperties } from "react";
import "./number-drift.css";

export type NumberDriftProps = {
value: number;
locale?: string;
format?: Intl.NumberFormatOptions;
prefix?: string;
suffix?: string;
className?: string;
};

function sequence(
previous: number | null,
next: number,
direction: number,
): { items: number[]; from: number; to: number; duration: number } {
if (previous === null || previous === next || direction === 0) {
return { items: [next], from: 0, to: 0, duration: 240 };
}
if (direction > 0) {
const items = [previous];
let digit = previous;
while (digit !== next) {
digit = (digit + 1) % 10;
items.push(digit);
}
return {
items,
from: 0,
to: -(items.length - 1),
duration: Math.min(420, 220 + items.length * 36),
};
}
const items = [next];
let digit = next;
while (digit !== previous) {
digit = (digit + 1) % 10;
items.push(digit);
}
return {
items,
from: -(items.length - 1),
to: 0,
duration: Math.min(420, 220 + items.length * 36),
};
}

function DriftDigit({
previous,
digit,
direction,
}: {
previous: number | null;
digit: number;
direction: number;
}) {
const built = sequence(previous, digit, direction);
const style = {
"--nd-from": `${built.from}em`,
"--nd-to": `${built.to}em`,
"--nd-duration": `${built.duration}ms`,
} as CSSProperties;

return (
<span className="nd-digit">
<span className="nd-track" style={style}>
{built.items.map((value, index) => (
<span className="nd-cell" key={`${value}-${index}`}>
{value}
</span>
))}
</span>
</span>
);
}

/**
* NUMBER DRIFT
*
* Formats with Intl.NumberFormat, then aligns the result from the right
* so separators and signs keep their place while digits roll. Each
* changed digit runs a short directional strip; unchanged digits keep
* their DOM and do not move. The visual is aria-hidden and the final
* formatted value is exposed once, so assistive technology never hears
* animation frames.
*/
export function NumberDrift({
value,
locale,
format,
prefix,
suffix,
className,
}: NumberDriftProps) {
const formatKey = format ? JSON.stringify(format) : "";
const formatter = useMemo(
() => new Intl.NumberFormat(locale, format),
// The serialised options are the stable identity of the formatter.
// eslint-disable-next-line react-hooks/exhaustive-deps
[locale, formatKey],
);
const text = formatter.format(Number.isFinite(value) ? value : 0);
const previous = useRef({ text, value });
const old = previous.current;
const direction = value > old.value ? 1 : value < old.value ? -1 : 0;

useEffect(() => {
previous.current = { text, value };
}, [text, value]);

const oldChars = Array.from(old.text);
const chars = Array.from(text);
const visual = chars.map((char, index) => {
const fromRight = chars.length - index;
const oldIndex = oldChars.length - fromRight;
const oldChar = oldIndex >= 0 ? oldChars[oldIndex] : "";
if (/\d/.test(char)) {
const nextDigit = Number(char);
const previousDigit = /\d/.test(oldChar) ? Number(oldChar) : null;
const changed = previousDigit !== nextDigit;
if (!changed) {
return (
<span className="nd-static nd-static--digit" key={`d-${fromRight}`}>
{char}
</span>
);
}
return (
<DriftDigit
key={`d-${fromRight}-${old.text}-${text}-${oldChar}`}
previous={previousDigit}
digit={nextDigit}
direction={direction}
/>
);
}
return (
<span className="nd-static" key={`s-${index}-${char}`}>
{char}
</span>
);
});

const accessible = `${prefix ?? ""}${text}${suffix ?? ""}`;

return (
<span
className={`nd-root${className ? ` ${className}` : ""}`}
data-changing={old.text !== text ? "true" : "false"}
>
<span className="nd-visual" aria-hidden="true">
{prefix ? <span className="nd-affix">{prefix}</span> : null}
{visual}
{suffix ? <span className="nd-affix">{suffix}</span> : null}
</span>
<span className="nd-sr">{accessible}</span>
</span>
);
}
components/lab/number-drift/number-drift.css— press enter to show or hide the source
css
.nd-root {
display: inline-flex;
align-items: baseline;
min-width: 0;
color: inherit;
font: inherit;
font-variant-numeric: tabular-nums;
font-feature-settings: "tnum" 1;
white-space: nowrap;
}

.nd-visual {
display: inline-flex;
align-items: center;
line-height: 1;
}

.nd-static,
.nd-affix {
display: inline-block;
line-height: 1;
}

.nd-static--digit {
width: 1ch;
text-align: center;
}

.nd-affix {
white-space: pre;
}

.nd-digit {
position: relative;
display: inline-block;
width: 1ch;
height: 1em;
overflow: hidden;
vertical-align: baseline;
}

.nd-track {
display: flex;
flex-direction: column;
animation: nd-roll var(--nd-duration, 280ms)
cubic-bezier(0.22, 1, 0.36, 1) both;
will-change: transform;
}

.nd-cell {
display: flex;
align-items: center;
justify-content: center;
height: 1em;
line-height: 1;
}

.nd-sr {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
}

@keyframes nd-roll {
from {
transform: translate3d(0, var(--nd-from, 0em), 0);
}
to {
transform: translate3d(0, var(--nd-to, 0em), 0);
}
}

@media (prefers-reduced-motion: reduce) {
.nd-track {
animation: none;
transform: translate3d(0, var(--nd-to, 0em), 0);
}
}