Implementing Scroll Based Animations using React and GSAP
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.
Step 1: Create a context that will wrap our components and provide the necessary functionality
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.
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.
Next, we will create a GSAP timeline and use a scroll trigger to target an element, and set the start and endpoint for animation.
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().
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.