I'm looking for a way to animate a counter in React.
For the sake of example, I have 3 components with the following structure:
(Master is the parent of logicComponent and Counter)
The logic component passes a number to the master component, which passes it to the counter component that should perform the animation. The logical component sends numbers incrementally, that is, every time something happens, it sends an update.
For example, logicCounter calls Master ten times to increment the counter, I expect Counter to render 10 times, displaying 10 numbers. Everything I've tried so far displays the final number (10) without any increments.
After searching for a solution I came across Window.requestAnimationFrame() and I was looking for a proper way to implement it in React.
I'm trying to avoid using 3rd party npms/libraries.
Hope for your help/ideas. Thanks.
P粉2140893492023-10-22 09:06:16
For animated counters in React-JS, I use 'react-count' : a configurable React component wrapper around "CountUp.js".
Please refer to: https://github.com/glennreyes/react-countup. Check out the live demo: https://tr8tk.csb.app/ step:
Install:
*npm install react-countup --save* or *yarn add react-countup*
Simple example:
import React from 'react'; import { render } from 'react-dom'; import CountUp from 'react-countup'; render( <CountUp start={0} end={160526} />, document.getElementById('root') );
Advanced Example:
import React from 'react'; import { render } from 'react-dom'; import CountUp from 'react-countup'; const onComplete = () => { console.log('Completed!'); }; const onStart = () => { console.log('Started!'); }; render( <CountUp className="account-balance" start={160527.0127} end={-875.0319} duration={2.75} useEasing={true} useGrouping={true} separator=" " decimals={4} decimal="," prefix="EUR " suffix=" left" onComplete={onComplete} onStart={onStart} />, document.getElementById('root'), );