useInView
A simple state hook for when an element is within the viewport.
useInView
is a tiny (0.6kb) hook that detects when the provided element is within the viewport.
function Component() { const ref = useRef(null) const isInView = useInView(ref)
return <div ref={ref} />}
#Usage
Import useInView
from Framer Motion.
import { useInView } from "framer-motion"
useInView
can track the visibility of any HTML element. Pass a ref
object to both useInView
and the HTML element.
function Component() { const ref = useRef(null) const isInView = useInView(ref)
return <div ref={ref} />}
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
.
useEffect(() => { console.log("Element is in view: ", isInView)}, [isInView])
#Options
#root: RefObject<HTMLElement>
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.
function Carousel() { const container = useRef(null) const ref = useRef(null) const isInView = useInView({ root: container }) return ( <div ref={container} style={{ overflow: "scroll" }}> <div ref={ref} /> </div> )}
#margin: string
One or more margins to apply to the root
element or window viewport. This can extend or contract the point at which the element is considered inside the viewport.
Margins must be defined as px
or %
.
const isInView = useInView({ margin: "0px 100px -50px 0px"})
Note: For browser security reasons, margin
won't take affect within cross-origin iframes unless `root` is explicitly defined.
#once: boolean
By setting once: true
, once an element is in view, useInView will stop observing the element and always return true
.
const isInView = useInView(ref, { once: true })
#amount: "some" | "all" | number
The amount of an element that needs to enter the viewport for useInView
to return true
.
This is defined as a number between 0
and 1
, where 0
is some or any of the element, and 1
is all of the element.