Thinking UI

Animated Number

Digits roll into place like an odometer when the value changes.

Code

components/thinking-ui/animated-number.tsx
"use client";

import { motion } from "motion/react";
import { useMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";

export type AnimatedNumberProps = {
  value: number;
  /** Turns the number into display text. Digits roll; everything else is static. */
  format?: (value: number) => string;
  className?: string;
};

const defaultFormat = (n: number) => n.toLocaleString("en-US");

export function AnimatedNumber({ value, format = defaultFormat, className }: AnimatedNumberProps) {
  const text = format(value);
  const chars = Array.from(text);

  return (
    <span aria-label={text} role="text" className={cn("inline-flex font-mono tabular-nums leading-none", className)}>
      {chars.map((char, i) => {
        // Key from the right so units stay units when the number grows
        const key = chars.length - i;
        return /\d/.test(char) ? (
          <Digit key={`d${key}`} digit={Number(char)} />
        ) : (
          <span key={`s${key}`} aria-hidden>
            {char}
          </span>
        );
      })}
    </span>
  );
}

function Digit({ digit }: { digit: number }) {
  const m = useMotion();
  return (
    <span aria-hidden className="relative inline-block h-[1em] w-[1ch] overflow-hidden">
      <motion.span
        className="absolute inset-x-0 top-0 flex flex-col"
        initial={{ y: "0em" }}
        animate={{ y: `${-digit}em` }}
        transition={m.spring("emphasis")}
      >
        {Array.from({ length: 10 }, (_, n) => (
          <span key={n} className="block h-[1em] text-center">
            {n}
          </span>
        ))}
      </motion.span>
    </span>
  );
}

Motion notes

  • Each digit is its own column, so only the digits that change move.
  • Columns are keyed from the right, so the ones digit stays the ones digit as the number grows.
  • Rolls on the emphasis spring. Playful overshoots slightly past the target digit.

Installation

  1. 1

    Install dependencies

    Terminal
    npm install motion clsx tailwind-merge
  2. 2

    Add the design tokens and motion system (once per project)

    Copy styles/tokens/*, lib/motion.tsx and lib/utils.ts from Get started.

  3. 3

    Paste the source into components/thinking-ui/animated-number.tsx

    Copy it from the Code tab, or use Copy prompt to let your coding agent do all of this.

Usage

Example
<AnimatedNumber value={credits} />

Props

PropTypeDefaultDescription
valuenumber—The number to show.
format(value: number) => stringtoLocaleStringFormats the display text.