
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Auto Scrolling Animation in React JS Using React Spring
In this article, we will see how to create a scroll to top animation in React JS using the react-spring package.
First create a react project −
npx create-react-app tutorialpurpose
Now go to the project directory −
cd tutorialpurpose
Example
Install the react-spring package −
npm install react-spring
react-spring is used to add Spring concept based animations to our website.
Next,Add the following lines of code in App.js −
import React,{useState} from 'react' import { useSpring, animated } from 'react-spring' export default function App(){ const [flip, set] = useState(false) const words = ['We', 'came.', 'We', 'saw.', 'We', 'hold', 'it s', 'hands.'] const { scroll } = useSpring({ scroll: (words.length - 1) * 50, from: { scroll: 0 }, reset: true, reverse: flip, delay: 200, onRest: () => set(!flip), }) return ( <animated.div style={{ position: 'relative', width: '100%', height: 60, overflow: 'auto', fontSize: '1em', marginTop:200 , border:"1px solid black" }} scrollTop={scroll}> {words.map((word, i) => ( <div key={`${word}_${i}`} style={{ width: '100%', height: 50, textAlign: 'center' }}> {word} </div> ))} </animated.div> ) }
Explanation
In the scroll attribute of spring object, we defined how much we have to scroll. If you change the value from 50 to 20, it will only scroll three words
The from attribute indicates from where to start scrolling; "0" means start scrolling from the beginning.
We also have some extra attributes like
reset which is meant for looping
reverse signifies when the counting should start or end,
delay to introduce time delay between animation, and
onRest indicates what to do on when the counting stops.
Output
On execution, it will produce the following output −