How to Add React Scroll Effects With The AOS Library

icon

Written by

Silvia O'Dwyer

icon

Post date

2023-06-24

icon
icon

Views

icon

Shares

Welcome! In this guide, we're going to be taking a look at how to add AOS to your React project so that you can add cool scrolling effects and animations to your site.

Scroll animations can be an excellent addition to landing pages and can add some interactive flair to a website. I've added these types of effects to my landing pages and have found the AOS library to be one of the best out there for this purpose.

Let's get started!

1. Install AOS 

Firstly, install the AOS package via NPM:

npm i aos

2. Import Library and CSS

Then, import the library and CSS required in order for the scroll animations to work:

import AOS from "aos";
import "aos/dist/aos.css";

3. Initialize Library

Once you've imported the library and CSS, it's time to initialize AOS in the `useEffect` Hook:

useEffect(() => {
    AOS.init({
      disable: "phone",
      duration: 700,
      easing: "ease-out-cubic",
    });
  }, []);

In the example code snippet above, the animations are only shown for desktop devices and disabled for mobile devices.

If you'd only like the scroll animation to display once, simply set the once property to `true`:

useEffect(() => {
    AOS.init({
      once: true,
      disable: "phone",
      duration: 700,
      easing: "ease-out-cubic",
    });
  }, []);

4. Add Data Attributes

Now that the library has been initialized, it's time to add the animations to the elements. Simply choose an element (such as a heading or section) that you would like to animate, and add a data-aos data attribute to this. The value is the name of the type of animation. The full list can be viewed on the official AOS website, so be sure to take a look at that for the complete list. You can also preview each effect and element also.

<h1 data-aos="zoom-y-out">Sample heading</h1>

If you'd like to add a delay to the animation, simply set the data-aos-delay data attribute to the delay number in milliseconds:

<h1 data-aos="zoom-y-out" data-aos-delay="50">Sample heading</h1>

Pre-built Landing Page Examples With AOS Effects

We're also building a selection of landing pages that make use of the AOS library, so if you'd like to be notified when these are released, be sure to join the newsletter, where I send a weekly email with lots of useful links and resources related to frontend development.

Conclusion

Thanks very much for reading this tutorial, I hope that you've found it useful for your React project!

Scroll effects can be an excellent way of adding some dynamic animations to your landing page, and can help showcase the various features of the product or web app. The AOS library is an excellent resource, and I'd definitely recommend trying it out!