Create an animated counter in React.js: a step-by-step guide
P粉635509719
P粉635509719 2023-10-21 19:46:40
0
1
688

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:
    • Logical Component
    • Counter

(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粉635509719
P粉635509719

reply all(1)
P粉214089349

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'),
);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template