SECRET OF CSS

Simple React Scroll Animations With Zero Dependencies | by Bret Cameron | Sep, 2022


React Hooks, CSS, and the Intersection Observer API

1*YPM1443ovctut3cYv9Tewg
Photo by Tim Schmidbauer on Unsplash

One of the most common effects in brochure websites is a fade-in or float-in animation that occurs during scrolling, shortly after the element enters the user’s screen.

To achieve these effects, developers typically reach for an animation library. But for most websites, there is no need for this additional overhead!

Using CSS and the native Intersection Observer API, we can create a simple and performant method for animating elements as users scroll down our page. In this article, we’ll see how to achieve this with React. The examples in this article also use TypeScript.

Whenever one of our React components is mounted, we can create a new IntersectionObserver that will observe when it intersects with the browser viewport.

The preferred way to reference elements in React is via refs, so we’ll use ref as our first argument. The second argument allows us to set an offset amount so that the animation triggers a set distance from the edge of the window — with "0px" being exactly on the edge.

Make sure to run unobserve in the returned cleanup function so we don’t continue observing a component once it has dismounted.

For a simple fade-in-and-up effect, we can simply alter the opacity and translate CSS properties depend on whether the element is on screen or not.

Then, in our code, we can simply call:

<AnimateIn>
<h1>Hello World</h1>
</AnimateIn>

We could stop here, but with a few additional tweaks, we can turn this pattern into something more customisable and reusable.

If we want to extend the range of possible animations, we need to make our component a little more generic, allowing developers to pass in their own CSS for the from and to states.

Now, if we wanted to create a library of simple animations, we could easily build this using our AnimateIn component. For example:

As a personal preference, I like grouping these components as part of an Animate object, which I then export:

export const Animate = {
FadeIn,
FadeUp,
ScaleIn,
};

We can then call an animation like this:

<Animate.ScaleIn>
<h1>Hello World</h1>
</Animate.ScaleIn>

We now have access to a comparable level of animation to most brochure websites without needing additional dependencies!

For a working example, check out the CodePen below:

Thanks for reading! Stay tuned for more.



News Credit

%d bloggers like this: