Animated Counter
Number that counts from a start value to its final value the first time it scrolls into view, formatted with Intl. The server render and screen readers get the final value only.
How it differs. Interpolates the whole value on an animation frame loop. The moving node is hidden from assistive technology and a visually hidden sibling carries the final value.
Install
pnpm dlx shadcn@latest add @hazine/animated-counterAdds 1 file.
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/animated-counter.tsx, 90 lines
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
const MAX_DURATION = 500
export interface AnimatedCounterProps
extends Omit<React.ComponentProps<"span">, "ref"> {
/** Final value. The server render and assistive technology only ever see this. */
value: number
/** Value the count starts from. */
from?: number
/** Milliseconds, capped at 500. */
duration?: number
locale?: string
/** Passed to Intl.NumberFormat, for example { style: "currency", currency: "USD" }. */
formatOptions?: Intl.NumberFormatOptions
prefix?: string
suffix?: string
}
export function AnimatedCounter({
value,
from = 0,
duration = MAX_DURATION,
locale = "en-US",
formatOptions,
prefix = "",
suffix = "",
className,
...props
}: AnimatedCounterProps) {
const ref = React.useRef<HTMLSpanElement>(null)
// Null means at rest: the final value is shown.
const [frameValue, setFrameValue] = React.useState<number | null>(null)
const formatter = new Intl.NumberFormat(locale, formatOptions)
React.useEffect(() => {
const node = ref.current
if (!node || from === value) return
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
const length = Math.min(Math.max(duration, 1), MAX_DURATION)
const whole = Number.isInteger(from) && Number.isInteger(value)
let frame = 0
const observer = new IntersectionObserver(
([entry]) => {
if (!entry?.isIntersecting) return
observer.disconnect()
const start = performance.now()
const tick = (now: number) => {
const progress = Math.min((now - start) / length, 1)
const eased = 1 - Math.pow(1 - progress, 3)
const between = from + (value - from) * eased
// Whole endpoints count through whole numbers only.
setFrameValue(progress < 1 ? (whole ? Math.round(between) : between) : null)
if (progress < 1) frame = requestAnimationFrame(tick)
}
frame = requestAnimationFrame(tick)
},
{ threshold: 0.5 }
)
observer.observe(node)
return () => {
observer.disconnect()
cancelAnimationFrame(frame)
}
}, [value, from, duration])
return (
<span
ref={ref}
data-slot="animated-counter"
className={cn("tabular-nums", className)}
{...props}
>
<span aria-hidden="true">
{prefix}
{formatter.format(frameValue ?? value)}
{suffix}
</span>
<span className="sr-only">
{prefix}
{formatter.format(value)}
{suffix}
</span>
</span>
)
}
The demo in the preview, 27 lines
import { AnimatedCounter } from "@/components/hazine/animated-counter"
export default function AnimatedCounterDemo() {
return (
<dl className="grid gap-6">
<div>
<dt className="text-sm text-muted-foreground">Invoices sent this year</dt>
<dd className="mt-1 text-4xl font-semibold tracking-tight">
<AnimatedCounter value={12480} />
</dd>
</div>
<div>
<dt className="text-sm text-muted-foreground">Collected in October</dt>
<dd className="mt-1 text-2xl font-semibold tracking-tight">
<AnimatedCounter
value={48250}
formatOptions={{
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
}}
/>
</dd>
</div>
</dl>
)
}
Props7
- valuerequired
- number
- Final value. The server render and assistive technology only ever see this.
- from
- number = 0
- Value the count starts from.
- duration
- number = MAX_DURATION
- Milliseconds, capped at 500.
- locale
- string = "en-US"
- formatOptions
- Intl.NumberFormatOptions
- Passed to Intl.NumberFormat, for example { style: "currency", currency: "USD" }.
- prefix
- string = ""
- suffix
- string = ""
Also accepts every prop of Omit<React.ComponentProps<"span">, "ref">.
Accessibility
- Pattern
- Landmarks and headings
- Keyboard
- Nothing to operate. The item has no focusable parts.
- Screen reader
The animated span is aria-hidden. A visually hidden sibling holds the final formatted value, so intermediate numbers are never read.
- Reduced motion
- The final value is shown at once and nothing counts.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies0
None. The item is one self-contained file.
Tokens shipped0
None. The item is styled by the tokens your theme already has.