Creating a parallax scrolling effect in React using react-spring.mp4


In this article, we will see how to make the popular parallax effect in React.js using react-spring animation library. Parallax is a displacement or difference in the apparent position of an object viewed along two different lines of sight, and is measured by the angle of inclination between those two lines. Parallax scrolling is an effect where the background content moves at a different speed than the foreground content. So, let's get started.

First create a React project −

npx create-react-app tutorialpurpose

Go to the project directory −

cd tutorialpurpose

Example

Install the following packages −

npm install react-spring
npm i --save @react-spring/parallax

react-spring is used to add spring concept based animations to our website and this library will be used to add different type of animations. react-spring/parallax will be used to add parallax effect.

Add the following lines of code in App.js

import React, { useState } from "react";
import { Parallax, ParallaxLayer } from "@reactspring/parallax";

export default function App() {
   return (
      <Parallax pages={2} style={{ top: "0", left: "0" }}>
         <ParallaxLayer
            offset={0}
            speed={2.5}
            style={{
               display: "flex",
               justifyContent: "center",
               alignItems: "center",
            }}
         >
         <p>Scroll down</p>
         </ParallaxLayer>
         <ParallaxLayer
            offset={1}
            speed={2}
            style={{ backgroundColor: "#ff6d6d" }} />

         <ParallaxLayer
            offset={1}
            speed={0.5}
            style={{
               display: "flex",
               justifyContent: "center",
               alignItems: "center",
               color: "white",
            }}>
            <p>Scroll up
         </ParallaxLayer>
      </Parallax>
   );
}

Explanation

We first created a parallax container. The page attribute indicates how much the parallax layer container will take space on 100% viewport.

Then we created 3 parallax layer components, inside which we have our content. It has attributes to define the movement like speed. Any content inside the parallaxLayer will apply the parallax effect to the content inside it.

Output

On execution, it will produce the following output −

Updated on: 28-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements