-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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