useIntersectionObserver()
useIntersectionObserver(
reference
,options
?):boolean
Defined in: src/hooks/dom/useIntersectionObserver.ts:40
A custom React hook that uses the Intersection Observer API to determine if an element is visible within the viewport.
Parameters
reference
RefObject
<HTMLElement
>
A React ref pointing to the target DOM element.
options?
IntersectionObserverInit
= {}
Configuration options for the IntersectionObserver (e.g., threshold, root, rootMargin).
Returns
boolean
isIntersecting
- Whether the element is currently visible in the viewport.
Example
tsx
import { useRef } from 'react';
import { useIntersectionObserver } from '@zl-asica/react';
const MyComponent = () => {
const ref = useRef<HTMLDivElement>(null);
const isVisible = useIntersectionObserver(ref, { threshold: 0.5 });
return (
<div>
<div style={{ height: '150vh', background: 'lightgray' }}>Scroll down</div>
<div
ref={ref}
style={{
height: '100px',
backgroundColor: isVisible ? 'green' : 'red',
}}
>
{isVisible ? 'Visible' : 'Not Visible'}
</div>
<div style={{ height: '150vh', background: 'lightgray' }} />
</div>
);
};