Creating a reveal effect on a webpage can significantly enhance user engagement and provide a dynamic browsing experience.
The useIntersectionReveal()
hook can be employed to detect when an element enters the viewport and trigger animations or transitions.
It can be integrated with CSS animations or JavaScript libraries such as react-spring
or framer-motion
to animate text, images,
or other elements as they come into view,
making the content more interactive and visually appealing.
Usage
useIntersectionReveal(sectionRef, trackOnce, options)
gives you the ability to track whether the element (tracked with sectionRef
)
enters the viewport. It takes two arguments:
sectionRef
: A reference to the element to observe.trackOnce
: A boolean that determines whether to observe the element only once. Default value:false
.options
: Allow customizing the observer. You can pass anIntersectionObserverOptions
object to configure the observer (opens in a new tab).
import { useIntersectionReveal } from '@react-scrollytelling/core';
// inside a React component
const trackOnce = true;
const sectionRef = useRef<HTMLDivElement>(null);
const { isIntersecting } = useIntersectionReveal(sectionRef, trackOnce);
return (
<div
ref={sectionRef}
style={{
opacity: isIntersecting ? 1 : 0,
transform: isIntersecting ? 'translateY(0)' : 'translateY(10px)',
}}
>
Play animation when it enters the viewport
</div>
);
Example
Reveal multiple times
trackOnce
is false by default, which means that we want to trigger the animation every time the element enters the viewport:
Reveal once
trackOnce
is true, which means that we want to trigger the animation only once when the element enters the viewport.
This is a very common use case for product page animations/lazy loading images:
Behind the scenes
useIntersectionReveal()
hook is a simple wrapper around the useIntersectionObserver()
hook,
which uses the Intersection Observer API (opens in a new tab) to detect when an element enters the viewport, and changes the isIntersecting
state accordingly,
and disconnect the observer when trackOnce
is true and the element is already in view.