shadcn-ahooks

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.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useInViewport.json

Observe 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

PropertyDescriptionTypeDefault
targetDOM elements or Ref, support arrayTarget | Target[]-
optionsSettingOptions | undefined-

Options

More information refer to Intersection Observer API

PropertyDescriptionTypeDefault
thresholdEither a single number or an array of numbers which indicate at what percentage of the target's visibility the ratio should be executednumber | number[]-
rootMarginMargin around the rootstring-
rootThe 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>-
callbackTriggered when the callback of IntersectionObserver is called(entry: IntersectionObserverEntry) => void-

Result

PropertyDescriptionType
inViewportIs visibleboolean | undefined
ratioCurrent visible ratio, updated every time the node set by options.threshold is reachednumber | undefined

On this page