useInViewport
Observe whether the element is in the visible area, and the visible area ratio of the element. More information refer to [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
Overview
Observe whether the element is in the visible area, and the visible area ratio of the element. More information refer to Intersection Observer API.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.jsonObserve whether the element is in the visible area, and the visible area ratio of the element. More information refer to Intersection Observer API.
Examples
Default usage
Observe the visible area ratio of element
- Observe element visible area ratio
- Pass in options.threshold, you can control the ratio to be triggered when the visible area reach every threshold. options.root can control the parent element, in this example, visible will not change relative to the browser viewport.
Listening content scrolling selection menu
- Pass the callback that is triggered when the callback of IntersectionObserver is called, so you can do some customization.
API
type Target = Element | (() => Element) | React.MutableRefObject<Element>;
const [inViewport, ratio] = useInViewport(
target: Target | Target[],
options?: Options
);Params
| Property | Description | Type | Default |
|---|---|---|---|
| target | DOM elements or Ref, support array | Target | Target[] | - |
| options | Setting | Options | undefined | - |
Options
More information refer to Intersection Observer API
| Property | Description | Type | Default |
|---|---|---|---|
| threshold | Either a single number or an array of numbers which indicate at what percentage of the target's visibility the ratio should be executed | number | number[] | - |
| rootMargin | Margin around the root | string | - |
| root | 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 null. | Element | Document | () => (Element/Document) | MutableRefObject<Element> | - |
| callback | Triggered when the callback of IntersectionObserver is called | (entry: IntersectionObserverEntry) => void | - |
Result
| Property | Description | Type |
|---|---|---|
| inViewport | Is visible | boolean | undefined |
| ratio | Current visible ratio, updated every time the node set by options.threshold is reached | number | undefined |