useInView
useInView
is a tiny (0.6kb) hook that detects when the provided element is within the viewport. It can be used with any React element.
Usage
Import useInView
from Motion:
useInView
can track the visibility of any HTML element. Pass a ref
object to both useInView
and the HTML element.
While the element is outside the viewport, useInView
will return false
. When it moves inside the view, it'll re-render the component and return true
.
Effects
useInView
is vanilla React state, so firing functions when isInView
changes is a matter of passing it to a useEffect
.
Options
useInView
can accept options to define how the element is tracked within the viewport.
root
By default, useInView
will track the visibility of an element as it enters/leaves the window viewport. Set root
to be the ref of a scrollable parent, and it'll use that element to be the viewport instead.
margin
Default: "0px"
A margin to add to the viewport to change the detection area. Use multiple values to adjust top/right/bottom/left, e.g. "0px -20px 0px 100px"
.
]Note: For browser security reasons, margin
won't take affect within cross-origin iframes unless root
is explicitly defined.
once
Default: false
If true
, once an element is in view, useInView will stop observing the element and always return true
.
amount
Default: "some"
The amount of an element that should enter the viewport to be considered "entered". Either "some"
, "all"
or a number between 0
and 1
.
Example
Motion is open source. Sponsorships keep the project sustainable.
Every sponsor receives access to our private Discord, and an exclusive mobile and desktop wallpaper pack.