Open In App

How to trigger animations in a ReactJS app based on the scroll position ?

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

To trigger animations in a ReactJS app based on the scroll position we can define multiple component animations for the scroll values provided by windows.scrollY. When we scroll to that defined position, some animations get triggered. This provides a very nice user experience.

Prerequisite: 

Approach

to trigger animations in a ReactJS app based on the scroll position we will be using the react-animated-css-onscroll. we can define specific scroll values and trigger the animation whenever we scroll down to the component.

Syntax:

<AnimatedOnScroll animationIn="">
{Children}
</AnimatedOnScroll>

Parameters:

  • {Children}: The component wrapped within these tags
  • animationIn: The available animation names like bounce, flash, pulse, rubberBand, shake, and many more.

Features of react-animated-css-onscroll:

  • Lightweight module.
  • No need to create functions to know the current position of the component on the webpage.
  • A wide range of animations is available.
  • Very easy to work with.

Steps to Create React Application and Install Required Modules:

Step 1: Create the react project folder, for that open the terminal, and write the command npm create-react-app folder name, if you have already installed create-react-app globally.If you haven’t then install create-react-app globally by using the command npm -g create-react-app or can install locally by npm i create-react-app.

npm create-react-app project

Step 2: After creating your project folder(i.e. project), move to it by using the following command.

cd project

Step 3: To install the package, go to the terminal and run the command

npm i react-animated-css-onscroll

Step 4: Add the Animated.css in index.html file in public folder within the head tag.

<head>
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-animated-css-onscroll": "^1.2.1",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example 1: This exmple implements a simple bounce animation for component.

Javascript




// Filename - App.js
 
import { AnimatedOnScroll } from "react-animated-css-onscroll";
function App() {
    return (
        <div className="App">
            <h1 style={{ marginTop: "500px" }}>
                Hey Geek!
            </h1>
            <AnimatedOnScroll
                animationIn="bounceInRight"
                style={{
                    marginTop: "80px",
                    color: "green",
                }}
            >
                <h2>Welcome to Geeksforgeeks</h2>
            </AnimatedOnScroll>
        </div>
    );
}
 
export default App;


HTML




<!-- Filename - public/index.html -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <link rel="icon"
          href="%PUBLIC_URL%/favicon.ico" />
 
    <title>React App</title>
    <link rel="stylesheet"
             href=
</head>
 
<body
    style="text-align: center; margin: auto;">
    <div id="root"></div>
 
</body>
 
</html>


Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: This output will be visible on http://localhost:3000 on the brower window.

Example 2: This example implement components that display animation while scrolling down the page.

Javascript




// Filename - App.js
 
import { AnimatedOnScroll } from "react-animated-css-onscroll";
 
const Page = (props) => {
    const { children, ...rest } = props;
    return (
        <div {...rest} className="page">
            {children}
        </div>
    );
};
 
function App() {
    return (
        <div className="App">
            <h1 align="center">Hey! Geek Welcome</h1>
            <h2 align="center">Let's see some effects</h2>
            <div id="start">
                <AnimatedOnScroll animationIn="fadeInDownBig">
                    <Page children="fadeInDownBig" />
                </AnimatedOnScroll>
                <AnimatedOnScroll animationIn="bounceInLeft">
                    <Page children="bounceInLeft" />
                </AnimatedOnScroll>
                <AnimatedOnScroll animationIn="wobble">
                    <Page children="wobble" />
                </AnimatedOnScroll>
                <AnimatedOnScroll animationIn="tada">
                    <Page children="tada" />
                </AnimatedOnScroll>
                <AnimatedOnScroll animationIn="jello">
                    <Page children="jello" />
                </AnimatedOnScroll>
                <AnimatedOnScroll animationIn="bounceInRight">
                    <Page children="bounceInRight" />
                </AnimatedOnScroll>
                <AnimatedOnScroll
                    animationIn="bounce"
                    duration="1000"
                >
                    <Page children="bounce" />
                </AnimatedOnScroll>
            </div>
        </div>
    );
}
 
export default App;


HTML




<!-- Filename - public/index.html -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <link rel="icon"
        href="%PUBLIC_URL%/favicon.ico" />
 
    <title>React App</title>
    <link rel="stylesheet"
        href=
</head>
 
<body
    style="text-align: center; margin: auto;">
    <div id="root"></div>
 
</body>
 
</html>


CSS




/* Filename - index.css */
 
body {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont,
        "Segoe UI", "Roboto", "Oxygen", "Ubuntu",
        "Cantarell", "Fira Sans", "Droid Sans",
        "Helvetica Neue", sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
 
code {
    font-family: source-code-pro, Menlo, Monaco, Consolas,
        "Courier New", monospace;
}
.page {
    height: 30px;
    width: 300px;
    font-style: italic;
    margin-top: 20px;
    text-align: center;
    padding: 70px 0;
    font-size: 2rem;
    font-weight: 800;
}
 
#start {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
#start div:nth-child(2n) {
    background-color: rgb(6, 71, 6);
    color: white;
}


Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output:



Similar Reads

Hide scroll bar, but while still being able to scroll using CSS
To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below: -webkit- (Chrome, Safari, newer versions of Opera): .element::-webkit-scrollbar { width: 0 !important } -moz- (Firefox): .element { overflow: -mo
3 min read
How to Get and Set Scroll Position of an Element using JavaScript ?
In this article, we will learn how to get and set the scroll position of an HTML element using JavaScript. Approach: We will be using the HTML DOM querySelector() and addEventListener() methods and the HTML DOM innerHTML, scrollTop and scrollLeft properties. We create an HTML div element with an id of "scroll-element" and select it using the queryS
3 min read
Build an Image Search App with Infinite Scroll using React JS
This article delves into building a React-based image search app with infinite scroll. Users can search for images based on a query, and as they scroll down, additional images are fetched and shown. The Unsplash API is employed for searching and retrieving these images, resulting in a fully operational image search app with an integrated infinite s
3 min read
How to change the navbar color when you scroll in ReactJS ?
On scroll navbar color change in React highlights a sticky responsive navigation bar to navigate through web application pages. It provides an efficient way to navigate multiple pages in a single-page application. The following approach covers how to change the navbar color when you scroll through the page in ReactJS. It is a simple effect you can
4 min read
How to Create Scroll Indicator using ReactJS ?
Scroll Indicator in React JS refers to a representation of the length of the page visited or present on the screen. It shows the amount the pages that have been scrolled. PrerequisiteNode.js &amp; npm React JSstyled-componentsReact JS useState() hooks.Approach to create Scroll IndicatorTo create a Scroll Indicator using ReactJS we will use a scroll
2 min read
Create a scroll status in ReactJS using Material-UI
Progress bars at the top, showing scroll status are very common nowadays in webpages. Also, ReactJS and Material-UI go pretty well along with each other, React-JS being the most popular JavaScript framework for building UI components and Material-UI a library that provides various useful and reusable react components. Prerequisites:NodeJS or NPMRea
3 min read
jQuery trigger() Method
The jQuery trigger() method is a method that is used to trigger a specified event handler on the selected element. Syntax: $(selector).trigger(event, param1, param2)Note: Extra parameters can be passed in trigger() method. Example 1: This method triggered two methods to increase the value of the method. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt;
2 min read
How to trigger onchange event on input type=range while dragging in Firefox ?
Onchange: Onchange executes a JavaScript when a user changes the state of a select element. This attribute occurs only when the element becomes unfocused. Syntax: &lt;select onchange="function()"&gt; Attribute Value: It works on &lt;select&gt; element and fires the given JavaScript after the value is committed. Example: &lt;!DOCTYPE html&gt; &lt;ht
2 min read
How to trigger setInterval loop immediately using JavaScript ?
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time run. Below examples illustrate the above approach
2 min read
How to trigger HTML button after hitting enter button in textbox using JavaScript ?
In this article, we are given an HTML document containing a text area and the task is to trigger the button when the user hit Enter button. We can do it by using the "keyup", "keydown", or "keypress" event listener on the textbox depending on the need. When this event is triggered, we check if the key pressed is ENTER or not. If the key pressed is
4 min read