Detect whether an element is in view with the Intersection Observer API.
- isIntersecting: false
Usage
import { useIntersectionObserverState } from '@react-scrollytelling/core';
export const IntersectionSection = () => {
const sectionRef = useRef<HTMLDivElement>(null);
const { isIntersecting } = useIntersectionObserverState(sectionRef);
return (
<>
<section ref={sectionRef}>
<h1>Intersection Observer</h1>
<p>isIntersecting: {`${isIntersecting}`}</p>
</section>
</>
);
};
Parameters
The useIntersectionObserver
hook accepts the following parameters:
export function useIntersectionObserver(
sectionRef: React.RefObject<Element>,
options: IntersectionObserverOptions,
shouldObserve: boolean,
onObserve?: (isIntersecting: IntersectionObserverEntry) => void
) // ...
sectionRef
: A reference to the element to observe.options
: Allow customizing the observer. You can pass anIntersectionObserverOptions
object to configure the observer (opens in a new tab).shouldObserve
: A boolean that determines whether to observe the element. You can disable the observer by setting this value tofalse
. Default value:true
.onObserve
: A callback function that is called when the element is intersecting. The callback receives anIntersectionObserverEntry
object as an argument.