Skip to content

Instantly share code, notes, and snippets.

@bonface221
Created January 11, 2024 09:01
Show Gist options
  • Save bonface221/f1d4d42992ac71c4289702c7da0a5b3f to your computer and use it in GitHub Desktop.
Save bonface221/f1d4d42992ac71c4289702c7da0a5b3f 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