M
M
MarEeeeeee2021-04-05 21:21:58
React
MarEeeeeee, 2021-04-05 21:21:58

How to implement number changing animation using React.js?

There is a function that should create animations of running numbers (in the fragment, the insertion into the HTML code is cut out) I don’t quite understand how to properly adapt it for a react application?

const outNum = (num) => {
        let t = Math.random(time/(num/step))
        let n = 0;
        let interval = setInterval(() => {
            n = n + step;
            if(n == num){
                clearInterval(interval)
            }
        }, t);
        return n;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-04-06
@0xD34F

function Counter({ val, time }) {
  const [ currVal, setCurrVal ] = useState(0);

  useEffect(() => {
    currVal !== val && setTimeout(setCurrVal, time, currVal + 1);
  }, [ currVal ]);

  return <div>{currVal}</div>;
}

https://jsfiddle.net/jsxopeag/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question