Skip to main content

useIntersecting

Determine whether two elements intersect.

API

function useIntersecting(
target: EffectTarget<Element>,
options?: {
root?: EffectTarget<Element | Document>;
rootMargin?: string;
threshold?: number | number[];
}
): void;

type Nullable<T> = T | undefined | null;
type EffectTarget<T> =
| Nullable<T>
| (() => Nullable<T>)
| { current: Nullable<T> };

Params:

Results:

  • A boolean indicates whether the two elements are intersecting.

Example

Incomplete intersection
import React, { useRef } from "react";
import { useIntersecting } from "@lilib/hooks";

function Example() {
const rootRef = useRef(null);
const targetRef = useRef(null);

const intersecting = useIntersecting(targetRef, {
root: rootRef,
threshold: 1,
});

return (
<div ref={rootRef} style={{ height: 200, overflow: "auto" }}>
<div
ref={targetRef}
style={{
height: 100,
marginTop: 150,
marginBottom: 150,
backgroundColor: intersecting ? "orange" : "transparent",
}}
>
{intersecting ? "Complete intersection" : "Incomplete intersection"}
</div>
</div>
);
}

export default Example;