A React hook to detect if an HTML Element has been display in the viewport. This is easy to use. You just have to provide an react ref. By default it freeze the value when the element has been display. That is nice to triggered one time animation !
npm install react-viewport-detectjsx
import {useViewportDetection} from "react-viewport-detect";
import {useRef, useEffect} from "react" ;
const App () => {
const ref = useRef() ;
const isVisible = useViewportDetection(ref) ;
useEffect(() => {
console.log(isVisible) ;
},[isVisible]) ;
return (
React visible hook
Do I am visible ?
);
};
`
$3
`jsx
import {useViewportDetection} from "react-viewport-detect";
import {useRef, useEffect} from "react" ;
const App () => {
const ref = useRef() ;
const isVisible = useViewportDetection(ref, {freeze: false, threshold: 1}) ;
useEffect(() => {
console.log(isVisible) ;
},[isVisible]) ;
return (
React visible hook
Do I am visible ?
);
};
`
Function parameters
$3
| Parameter | Type | Description | Default |
|-----------------------------------------|-------|---------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
| ref | React ref | The React ref to detect | none |
| {rootMargin, root, threshold, freeze} | Array | Intersection Observer options + freeze. Freeze is to keep the value when it has been display once | {rootMargin = 0px, root = null, threshold = 0, freeze = true}` |