HomeServiceContact
JavaScript
min read
June 14, 2023
June 14, 2023

Implementing Scroll Based Animations using React and GSAP

Implementing Scroll Based Animations using React and GSAP
Table of contents

As computers are getting more powerful it is getting easier to achieve complex animations without compromising the fluidity and user experience. There are various JavaScript animation libraries available and most of them are pretty good. We at QED42 tried some of them and for the most part, we used GSAP which we think is kind of becoming an industry standard. GSAP is highly configurable and is just the right tool if you want to have scroll-based animations.

Smooth background change on scroll –

One thing that is eye-catching and easy to achieve, is smoothly changing background colour while scrolling. To implement this, we will change the wrapper component’s background colour as its child components move in and out of the viewport.

Source:qed42-js.netlify.app

Step 1: Create a context that will wrap our components and provide the necessary functionality

Scroll Based Animations using React and GSAP

Step 2:We will then import child components (named First, Second and Third), GSAP, and AnimationContext in our main app component. We are monitoring “currentBg” in the “useEffect” hook and whenever its value changes, the GSAP function gets executed. GSAP will change the background in 1 second which gives the fade-in effect.

Scroll Based Animations using React and GSAP

Step 3: To implement scroll-based triggers for the second and third components we will use GSAP.

The second component returns the following JSX, having a reference to wrapper element and text.

Scroll Based Animations using React and GSAP
Scroll Based Animations using React and GSAP

Next, we will create a GSAP timeline and use a scroll trigger to target an element, and set the start and endpoint for animation.

Scroll Based Animations using React and GSAP

ScrollTrigger has onEnter and onLeaveBack function which gets triggered when the trigger element passes through the scroll markers. That is where we change our background using context.

Note: The same effect can be achieved using gsap.to(), gsap.from() and other methods instead of gsap.timeline().

Scroll Based Animations using React and GSAP

The code for the above demo can be found at the following Github link.

What we learned from our hands-on experience is that animations should enforce, enhance the user behaviour and experience. The animations should not hinder action items in a way that it takes more time for users to interact with them. Therefore the background animation we saw above is very subtle and doesn’t cause any such hindrance.

Written by
Editor
No art workers.
We'd love to talk about your business objectives