Making a timer in React JS using reactspring animation


In this article, we will see how to create a timer in React using react-spring animation. Spring animation is a new type of method which is used to add animation in a different way. It is a more precise and modern way to add animation in React.js. Using react-spring, we can create effects like fade-in, fade-out, bounce, etc.

First create a React project −

npx create-react-app firstproject

Now go to the project directory −

cd firstproject

Example

Install the react-spring package −

npm install react-spring

react-spring is used to add spring concept based animations to our website. We can use this library to add different type of animations.

Let us now proceed to create the timer in React.JS.

Add the following lines of code in App.js

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
function Number() {
   const [flip, set] = useState(false);
   const { number } = useSpring({
      reset: true,
      reverse: flip,
      from: { number: 0 },
      number: 5,
      delay: 100,
      onRest: () => set(!flip),
   });
   return <animated.div>{number.to((n) => n.toFixed(2))}</animated.div>;
}
export default function App() {
   return (
      <div style={{ marginLeft: 500, marginTop: 200 }}>
         <Number />
      </div>
   );
}

Explanation

We create a spring object, which will count from 0 to 5.

Then we added some extra attributes like −

  • reset to start the loop; it is set to true,

  • reverse to indicate when the counting should start or end,

  • delay to delay the animation, and

  • onRest to indicate what to do when the counting stops.

  • n.toFixed(2) indicates how many digits to show after the decimal.

Output

On execution, it will produce the following output −

Updated on: 28-Sep-2021

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements