useIntersectionObserver
Handle the IntersectionObserver using this hook.
Parameters
- the IntersectionObserver callback function.
- the IntersectionObserver options, as well as the
ref
object of the target element.
INFO
the root
option of the observer is replaced by container
which is a function that returns the root element in this hook.
Return Values
Name | Type | Description |
---|---|---|
ref | RefObject | the target element reference. |
observer | RefObject | the IntersectionObserver object reference. |
Example Usage
TIP
Just use useInView if you want to check if an element is intersecting or not.
tsx
import { useIntersectionObserver } from 'react-pre-hooks';
export default function Example() {
const { ref } = useIntersectionObserver(
entries => {
const p = document.querySelector('p')!;
if (entries[0].isIntersecting) p.textContent = "it's in the view!";
else p.textContent = "it's not in the view!";
},
{ threshold: 0.8 }
);
return (
<main>
<p>Scroll down..</p>
<div ref={ref}></div>
</main>
);
}
import { useIntersectionObserver } from 'react-pre-hooks';
export default function Example() {
const { ref } = useIntersectionObserver(
entries => {
const p = document.querySelector('p')!;
if (entries[0].isIntersecting) p.textContent = "it's in the view!";
else p.textContent = "it's not in the view!";
},
{ threshold: 0.8 }
);
return (
<main>
<p>Scroll down..</p>
<div ref={ref}></div>
</main>
);
}