bundui svg logo
Bundui

Count Animation

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

0
import CountAnimation from "@/components/core/count-animation";

export default function CountAnimationExample() {
  return <CountAnimation number={60} className="font-semibold text-2xl lg:text-5xl" />;
}

Installation

Install the following dependencies:
npm install motion clsx tailwind-merge
Copy and paste the following code into your project:
"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 CountAnimation({
  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>
  );
}
Update the import paths to match your project setup.

Usage

import CountAnimation from "@/components/core/count-animation";

export default function CountAnimationExample() {
  return <CountAnimation number={60} className="font-semibold text-2xl lg:text-5xl" />;
}

Examples

Prefix

$0
import CountAnimation from "@/components/core/count-animation";

export default function CountAnimationPrefixExample() {
  return <CountAnimation number={200} prefix="$" className="font-semibold text-2xl lg:text-5xl" />;
}

Props

PropTypeDefault
className?
string
-
suffix?
string
-
prefix?
string
-
number
number
-