Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an animated counter in React.js?

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.

like image 529
alexunder Avatar asked Dec 29 '15 09:12

alexunder


2 Answers

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'),
);
like image 51
GPPanda Avatar answered Sep 23 '22 16:09

GPPanda


maybe you should try my package, if you are using react.

enter image description here

https://github.com/bluebill1049/react-flip-numbers

i have used it to create the above count down timer.

code example below:

import react from 'react';
import FlipNumbers from 'react-flip-numbers';

export default function SexyComponent(props) {
    return <div>
        <FlipNumbers
            height="12px"
            width="12px"
            color="red"
            background="white"
            startAnimation
            numbers="12345"
            numberStyle={{ color: "black" }}
      />
    </div>;
}
like image 45
Bill Avatar answered Sep 25 '22 16:09

Bill