0

Component

Odometer

A number whose digits roll into place like a car meter.

1284

Usage

<Odometer value={visits} minDigits={4} />

Source

Copy both files into your project. The component has no dependencies beyond React.

"use client";

import styles from "./odometer.module.css";

const DIGITS = "0123456789".split("");

type OdometerProps = {
  value: number;
  /** Pad with leading zeros to at least this many digits. */
  minDigits?: number;
  className?: string;
};

export function Odometer({ value, minDigits = 1, className }: OdometerProps) {
  const text = Math.max(0, Math.floor(value)).toString().padStart(minDigits, "0");

  return (
    <span className={[styles.odometer, className].filter(Boolean).join(" ")}>
      <span className={styles.readable}>{text}</span>
      {text.split("").map((digit, index) => (
        // Keyed from the right, so the ones column stays the ones column as the number grows.
        <span key={text.length - index} className={styles.window} aria-hidden="true">
          <span className={styles.strip} style={{ transform: `translateY(${-Number(digit) * 10}%)` }}>
            {DIGITS.map((n) => (
              <span key={n}>{n}</span>
            ))}
          </span>
        </span>
      ))}
    </span>
  );
}