Counter Animation

PreviousNext

Enhance user experience with count animation, dynamically animating numbers to draw attention to key data points.

Docs
bunduicomponent

Preview

Loading preview…
examples/motion/components/counter-animation/01/counter-animation.tsx
"use client";

import React from "react";
import { cn } from "@/lib/utils";
import { useMotionValue, useTransform, animate, useMotionValueEvent } from "motion/react";

type Props = {
  number: number;
  className?: string;
  prefix?: string;
  suffix?: string;
};

export default function CounterAnimation({ number, className, prefix, suffix }: Props) {
  const count = useMotionValue(0);
  const rounded = useTransform(count, Math.round);
  const [current, setCurrent] = React.useState(0);

  React.useEffect(() => {
    const animation = animate(count, number, { duration: 2 });
    return animation.stop;
  }, [count, number]);

  useMotionValueEvent(rounded, "change", (latest) => {
    setCurrent(latest);
  });

  return (
    <span className={cn(className)}>
      {prefix}
      {current}
      {suffix}
    </span>
  );
}

Installation

npx shadcn@latest add @bundui/counter-animation

Usage

import { CounterAnimation } from "@/components/counter-animation"
<CounterAnimation />