Created
January 11, 2024 09:01
-
-
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
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