Skip to content

Instantly share code, notes, and snippets.

@gustavomorinaga
Created January 22, 2022 11:14
Show Gist options
  • Select an option

  • Save gustavomorinaga/1d3b85551cb23258f93503deba4f48c1 to your computer and use it in GitHub Desktop.

Select an option

Save gustavomorinaga/1d3b85551cb23258f93503deba4f48c1 to your computer and use it in GitHub Desktop.
Code to make number animation on Framer Motion
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