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
- Defaults to
options?: Object
- Defaults to
{}
- Defaults to
options.onIntersect?: (isIntersecting: boolean, entry?: IntersectionObserverEntry) => void
- Defaults to
() => {}
- Callback fired on enter & on leave
- Defaults to
options.onEnter?: (entry?: IntersectionObserverEntry) => void
- Defaults to
() => {}
- Callback fired on enter
- Defaults to
options.onLeave?: (entry?: IntersectionObserverEntry) => void
- Defaults to
() => {}
- Callback fired on leave
- Defaults to
options.enabled?: boolean
- Defaults to
true
- Determine whether intersection observer should be enabled or not
- Defaults to
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
- Defaults to the browser viewport if not specified or if
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
- Defaults to
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
- JS
- TS
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>
);
}
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