({
value,
direction = 'up',
}: {
value: number
direction?: 'up' | 'down'
})
| 4 | import { useInView, useMotionValue, useSpring } from 'framer-motion' |
| 5 | |
| 6 | export default function Counter({ |
| 7 | value, |
| 8 | direction = 'up', |
| 9 | }: { |
| 10 | value: number |
| 11 | direction?: 'up' | 'down' |
| 12 | }) { |
| 13 | const ref = useRef<HTMLSpanElement>(null) |
| 14 | const motionValue = useMotionValue(direction === 'down' ? value : 0) |
| 15 | const springValue = useSpring(motionValue, { |
| 16 | damping: 100, |
| 17 | stiffness: 100, |
| 18 | }) |
| 19 | const isInView = useInView(ref, { once: true, margin: '-100px' }) |
| 20 | |
| 21 | useEffect(() => { |
| 22 | if (isInView) { |
| 23 | motionValue.set(direction === 'down' ? 0 : value) |
| 24 | } |
| 25 | }, [motionValue, isInView, value, direction]) |
| 26 | |
| 27 | useEffect( |
| 28 | () => |
| 29 | springValue.on('change', (latest) => { |
| 30 | if (ref.current) { |
| 31 | ref.current.textContent = Intl.NumberFormat('en-US').format( |
| 32 | latest.toFixed(0), |
| 33 | ) |
| 34 | } |
| 35 | }), |
| 36 | [springValue], |
| 37 | ) |
| 38 | |
| 39 | return <span ref={ref} /> |
| 40 | } |
nothing calls this directly
no outgoing calls
no test coverage detected