

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
- Related Questions & Answers
- Creating a Particle Animation in React JS
- Adding Lottie animation in React JS
- Making a tilt-on-hover effect in React JS without CSS
- Making a wobbling cube in React using react-three-fiber
- Making an axes helper in React using react-three-fiber
- Drawing arrows between DOM elements in React JS using react-archer
- SVG morphing in React JS
- Creating a Customizable Modal in React JS
- Using pointer light for better lighting in React JS with React-Three-Fiber
- SVG drawing in React JS frontend
- Creating a Map in React JS without using third-party API
- Creating a PDF in React JS using plain CSS and HTML
- Creating a Rich Text Editor in React JS
- Making a countdown timer with Python and Tkinter
- Auto-scrolling animation in React.js using react-spring