Intersection Observer Hooks
These hooks help you track when an element enters or leaves the viewport.
Table of Contents
useInView
useInView
This hook just wraps the react-intersection-observer
library which uses internally the IntersectionObserver
API. As some old browsers don't support it, useInView
also returns a supported
prop indicating if it's supported or not.
Usage
Parameters
It accepts a single object with the following props:
Name
Type
Default
Required
Description
root
Element
window
no
The Element that is used as the viewport for checking visibility of the target. Defaults to the browser viewport (window
) if not specified or if null.
rootMargin
string
"0px"
no
Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left).
threshold
number or array of numbers
0
no
Number between 0 and 1 indicating the percentage that should be visible before triggering. Can also be an array of numbers, to create multiple trigger points.
triggerOnce
boolean
false
no
Only trigger this method once
Return value
An object with the following properties:
Name
Type
Description
ref
React.RefObject
React reference object pointing to the DOM element. It must be passed to the element you want to track.
inView
boolean
Boolean indicating if the element is visible. The value is always true
if supported
is false
.
supported
boolean
Demo
This example project shows how to use the Intersection Observer Hook useInView
available in the @frontity/hooks
package or directly implemented in some components available at @frontity/components
.
Last updated