How to create an animated counter in React.js?

alexunder picture alexunder · Dec 29, 2015 · Viewed 14.8k times · Source

I'm looking for a way to animate a counter in React.

For the sake of the example, I have 3 components of the following structure:

  • Master:
    • logicComponent
    • Counter

(Master is the parent of logicComponent and Counter)

The logic component passes a number to the master who passes it to the Counter component that should do the animation. The logicComponent sends the numbers in an incremental manner, that is, each time that something happens there, it sends an update.

For example, the logicCounter invokes the Master ten times to increment the counter, I would've expected that the Counter will be rendered 10 times showing 10 numbers. All the things I've tried so far resulted in showing the final number (10) without any incrementation.

After looking for solutions, I came across Window.requestAnimationFrame() and I'm looking for a proper way to implement it in React.

I'm trying to avoid 3rd party npms/libraries.

Would love your help / ideas. Thanks.

Answer

Girija Prasad Panda picture Girija Prasad Panda · Jun 9, 2018

For an animated counter in React-JS, I use 'react-count' : A configurable React component wrapper around 'CountUp.js'.

Please Refer : https://github.com/glennreyes/react-countup. Check out live demo : https://glennreyes.github.io/react-countup/ Steps :

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'),
);