How can I animate a pure number from 0 to 100 with a transition config?
<motion.div>
{num}
</motion.div>
With Framer Motion 2.8 a new animate
function was released, which is a good fit for this use case:
import { animate } from "framer-motion";
import React, { useEffect, useRef } from "react";
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() {
return <Counter from={0} to={100} />;
}
Note that instead of updating a React state continuously, the DOM is patched manually in my solution to avoid reconciliation overhead.
See this CodeSandbox.