How to trigger animations on scroll in React?

To trigger animations on scroll in a React component, you can use the IntersectionObserver API. Here's a step-by-step guide on how to achieve this:

  1. Import the useEffect and useState hooks from the react package.
import React, { useState, useEffect } from 'react';
  1. Create a state variable to store the visibility of the element being observed and initialize it to false.
const [isVisible, setIsVisible] = useState(false);
  1. Use the useEffect hook to set up the IntersectionObserver when the component mounts. In the useEffect function, create a new instance of IntersectionObserver and pass a callback function that will be triggered when the element being observed intersects the viewport.
useEffect(() => { const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { setIsVisible(true); observer.unobserve(entry.target); } }); }); observer.observe(elementToObserve); return () => { observer.disconnect(); }; }, []);
  1. In the above code, elementToObserve is a reference to the DOM element you want to observe. You can obtain this reference using the useRef hook.
const elementToObserve = useRef(null);
  1. Finally, update your JSX code to pass the ref attribute to the element you want to observe.
<div ref={elementToObserve}> {isVisible ? <AnimatedComponent /> : null} </div>

In this setup, the AnimatedComponent will only be rendered when the observed element intersects the viewport. You can customize the animation logic inside the AnimatedComponent to achieve the desired effect.

This approach allows you to trigger animations on scroll in a React component using the IntersectionObserver API.