Skip to content

Instantly share code, notes, and snippets.

@iamlos
Forked from bonface221/index.tsx
Created March 13, 2025 08:52
Show Gist options
  • Save iamlos/1f9f1e72e84a5045057f57daf6332bf6 to your computer and use it in GitHub Desktop.
Save iamlos/1f9f1e72e84a5045057f57daf6332bf6 to your computer and use it in GitHub Desktop.
Framer motion animated counter up while component is in view in next js. For react remove use client and props
"use client";
import {
animate,
motion,
useInView,
useMotionValue,
useTransform,
} from "framer-motion";
import { useEffect, useRef } from "react";
type CounterProps = {
from: number;
to: number;
};
function AnimatedCounter({ from, to }: CounterProps) {
const count = useMotionValue(from);
const rounded = useTransform(count, (latest) => {
return Math.round(latest);
});
const ref = useRef(null);
const inView = useInView(ref);
// while in view animate the count
useEffect(() => {
if (inView) {
animate(count, to, { duration: 2 });
}
}, [count, inView, to]);
return <motion.span ref={ref}>{rounded}</motion.span>;
}
export { AnimatedCounter };
Usage..
<AnimatedCounter from={0} to={item.number} />+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment