Discord
Source code

use-intersection

Get information about intersection of given element with its scroll container
Import

Usage

Use hook to get information about intersection of given element with its scroll container or body element with Intersection Observer API:

Obscured
import { useIntersection } from '@mantine/hooks';
import { Paper, Text, useMantineTheme } from '@mantine/core';
function Demo() {
const containerRef = useRef();
const theme = useMantineTheme();
const [ref, observer] = useIntersection({
root: containerRef.current,
threshold: 1,
});
return (
<Paper elementRef={containerRef} style={{ overflowY: 'scroll', height: 300 }}>
<div style={{ paddingTop: 260, paddingBottom: 280 }}>
<Paper
elementRef={ref}
padding="xl"
style={{
backgroundColor: observer?.isIntersecting ? theme.colors.green[9] : theme.colors.red[9],
minWidth: '50%',
}}
>
<Text style={{ color: theme.white }} weight={700}>
{observer?.isIntersecting ? 'Fully visible' : 'Obscured'}
</Text>
</Paper>
</div>
</Paper>
);
}

API

Hook accepts IntersectionObserver's options as its only optional argument:

useIntersection({
root: someDomElement,
rootMargin: '0px',
threshold: 1.0,
});

Hook returns ref function that should be passed to the observed element, and the latest entry, as returned by IntersectionObserver's callback. See Intersection Observer API documentation to learn everything about options.

On the first render (as well as during SSR), or when no element is being observed, the entry is null.

const [ref, ioEntry] = useIntersection();
// With regular element:
<div ref={ref}>Observed</div>
// With Mantine component:
<Paper elementRef={ref}>Observed</Paper>

Definition

function useIntersection<T extends HTMLElement = any>(
options?: ConstructorParameters<typeof IntersectionObserver>[1]
): readonly [(element: T | null) => void, IntersectionObserverEntry];
Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback