Created
January 22, 2022 11:14
-
-
Save gustavomorinaga/1d3b85551cb23258f93503deba4f48c1 to your computer and use it in GitHub Desktop.
Code to make number animation on Framer Motion
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
| import { animate } from "framer-motion"; | |
| import React, { useEffect, useRef, useState } from "react"; | |
| import "./styles.css"; | |
| function Counter({ from, to }) { | |
| const nodeRef = useRef(); | |
| useEffect(() => { | |
| const node = nodeRef.current; | |
| const controls = animate(from, to, { | |
| duration: 1, | |
| onUpdate(value) { | |
| node.textContent = value.toFixed(2); | |
| } | |
| }); | |
| return () => controls.stop(); | |
| }, [from, to]); | |
| return <p ref={nodeRef} />; | |
| } | |
| export default function App() { | |
| const [from, setFrom] = useState(0); | |
| const [to, setTo] = useState(100); | |
| useEffect(() => { | |
| const intervalId = setInterval(() => { | |
| setFrom(to); | |
| setTo(Math.floor(Math.random() * 100)); | |
| }, 2000); | |
| return () => { | |
| clearInterval(intervalId); | |
| }; | |
| }, [to]); | |
| return <Counter from={from} to={to} />; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment