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:
useEffect
and useState
hooks from the react
package.import React, { useState, useEffect } from 'react';
false
.const [isVisible, setIsVisible] = useState(false);
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();
};
}, []);
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);
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.