@alemesa/react-use-intersection-observer
v1.0.3
Published
React Hook that uses the intersection observer API
Downloads
9
Maintainers
Readme
react-use-intersection-observer
React Hook that uses the intersection observer API
Usage
npm i @alemesa/react-use-intersection-observer
- Example Codesanbox:
- Simple Example: Element will trigger a single time and unobserve
import React, { useRef, useEffect } from "react";
import useIntersectionObserver from "@alemesa/react-use-intersection-observer";
const Header = React.memo(() => {
const elRef = useRef(null);
// Pass a reference to the custom hook
const intersected = useIntersectionObserver(elRef);
useEffect(() => {
if (intersected) {
// Intersected - do whatever you want
console.log("Intersected element");
}
}, [intersected]);
return <h3 ref={elRef}>Example</h3>;
});
export default Header;
- Custom Example: Element will trigger multiple time
import React, { useRef, useEffect } from "react";
import useIntersectionObserver from "@alemesa/react-use-intersection-observer";
const Header = React.memo(() => {
const elRef = useRef(null);
// Pass a reference to the custom hook and custom options
const intersected = useIntersectionObserver(elRef, {
triggerOnce: false,
threshold: 0.3,
rootMargin: "-150px"
});
useEffect(() => {
if (intersected) {
// Intersected - do whatever you want
console.log("Intersected element");
}
}, [intersected]);
return <h3 ref={elRef}>Example</h3>;
});
export default Header;
Contributors
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!