Skip to main content

useInView

Tracks an HTML element's visibility using Intersection Observer API.


API​

const [ref, isInView] = useInView(initialIsInView, {
onIntersect,
onEnter,
onLeave,
enabled,
root,
rootMargin,
threshold,
});

Options​

  • initialIsInView?: boolean
    • Defaults to false
    • Determine initial state of isInView
  • options?: Object
    • Defaults to {}
  • options.onIntersect?: (isIntersecting: boolean, entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on enter & on leave
  • options.onEnter?: (entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on enter
  • options.onLeave?: (entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on leave
  • options.enabled?: boolean
    • Defaults to true
    • Determine whether intersection observer should be enabled or not
  • options.root?: Element | Document
    • Defaults to the browser viewport if not specified or if null
    • The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target
  • options.rootMargin?: string
    • Defaults to all zeros
    • Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left), the values can be percentages
  • options.threshold?: number
    • Defaults to 0
    • Indicate at what percentage of the target's visibility the observer's callback should be executed

Returns​

  • ref: React.MutableRefObject
    • The ref used on JSX element
  • isInView: boolean
    • The state that determine whether the element has entered the viewport

Examples​

http://localhost:3000/
ℹī¸ Scroll down
Night
Sun
import { useInView } from 'react-power-ups';

export function Demo() {
const [ref, isInView] = useInView(false, {
onEnter: () => console.log('Element appeared in page'),
onLeave: () => console.log('Element dissappeared from page'),
});

return (
<div className={`transition-colors ${!isInView ? 'bg-slate-900 text-white' : 'bg-white'}`}>
<div className="absolute">
<span>{isInView ? 'Day' : 'Night'}</span>
</div>

<div style={{ height: 1000 }} />

<div ref={ref} className="sun">
Sun
</div>

<div style={{ height: 1000 }} />
</div>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-in-view.ts