react-intersection-observer
- Version 10.0.0
- Published
- 162 kB
- No dependencies
- MIT license
Install
npm i react-intersection-observeryarn add react-intersection-observerpnpm add react-intersection-observerOverview
Monitor if a component is inside the viewport, using IntersectionObserver API
Index
Functions
Classes
Interfaces
Type Aliases
Functions
function defaultFallbackInView
defaultFallbackInView: (inView: boolean | undefined) => void;What should be the default behavior if the IntersectionObserver is unsupported? Ideally the polyfill has been loaded, you can have the following happen: -
undefined: Throw an error -trueorfalse: Set theinViewvalue to this regardless of intersection state *
function observe
observe: ( element: Element, callback: ObserverInstanceCallback, options?: IntersectionObserverInit, fallbackInView?: boolean | undefined) => () => void;Parameter element
DOM Element to observe
Parameter callback
Callback function to trigger when intersection status changes
Parameter options
Intersection Observer options
Parameter fallbackInView
Fallback inView value. Function - Cleanup function that should be triggered to unregister the observer
function useInView
useInView: ({ threshold, delay, trackVisibility, rootMargin, root, triggerOnce, skip, initialInView, fallbackInView, onChange,}?: IntersectionOptions) => InViewHookResponse;React Hooks make it easy to monitor the
inViewstate of your components. Call theuseInViewhook with the (optional) [options](#options) you need. It will return an array containing aref, theinViewstatus and the current [entry](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry). Assign therefto the DOM element you want to monitor, and the hook will report the status.Example 1
import React from 'react';import { useInView } from 'react-intersection-observer';const Component = () => {const { ref, inView, entry } = useInView({threshold: 0,});return (<div ref={ref}><h2>{`Header inside viewport ${inView}.`}</h2></div>);};
function useOnInView
useOnInView: <TElement extends Element>( onIntersectionChange: IntersectionChangeEffect<TElement>, { threshold, root, rootMargin, trackVisibility, delay, triggerOnce, skip, }?: IntersectionEffectOptions) => (element: TElement) => (() => void) | undefined;React Hooks make it easy to monitor when elements come into and leave view. Call the
useOnInViewhook with your callback and (optional) [options](#options). It will return a ref callback that you can assign to the DOM element you want to monitor. When the element enters or leaves the viewport, your callback will be triggered.This hook triggers no re-renders, and is useful for performance-critical use-cases or when you need to trigger render independent side effects like tracking or logging.
Example 1
import React from 'react';import { useOnInView } from 'react-intersection-observer';const Component = () => {const inViewRef = useOnInView((inView, entry) => {if (inView) {console.log("Element is in view", entry.target);} else {console.log("Element left view", entry.target);}});return (<div ref={inViewRef}><h2>This element is being monitored</h2></div>);};
Classes
class InView
class InView extends React.Component< IntersectionObserverProps | PlainChildrenProps, State> {}## Render props
To use the
<InView>component, you pass it a function. It will be called whenever the state changes, with the new value ofinView. In addition to theinViewprop, children also receive arefthat should be set on the containing DOM element. This is the element that the IntersectionObserver will monitor.If you need it, you can also access the [
IntersectionObserverEntry](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry) onentry, giving you access to all the details about the current intersection state.```jsx import { InView } from 'react-intersection-observer';
const Component = () => ( {({ inView, ref, entry }) => ( <div ref={ref}> {
Header inside viewport ${inView}.} )} );export default Component; ```
## Plain children
You can pass any element to the
<InView />, and it will handle creating the wrapping DOM element. Add a handler to theonChangemethod, and control the state in your own component. Any extra props you add to<InView>will be passed to the HTML element, allowing you set theclassName,style, etc.```jsx import { InView } from 'react-intersection-observer';
const Component = () => ( <InView as="div" onChange={(inView, entry) => console.log('Inview:', inView)}> Plain children are always rendered. Use onChange to monitor state. );
export default Component; ```
constructor
constructor(props: IntersectionObserverProps | PlainChildrenProps);property handleChange
handleChange: (inView: boolean, entry: IntersectionObserverEntry) => void;property handleNode
handleNode: (node?: Element | null) => void;property lastInView
lastInView: boolean;property node
node: Element;method componentDidMount
componentDidMount: () => void;method componentDidUpdate
componentDidUpdate: (prevProps: IntersectionObserverProps) => void;method componentWillUnmount
componentWillUnmount: () => void;method observeNode
observeNode: () => void;method render
render: () => React.ReactNode;method unobserve
unobserve: () => void;Interfaces
interface IntersectionObserverProps
interface IntersectionObserverProps extends IntersectionOptions {}property children
children: (fields: RenderProps) => React.ReactNode;Children expects a function that receives an object contain an
inViewboolean andrefthat should be assigned to the element root.
interface IntersectionOptions
interface IntersectionOptions extends IntersectionObserverInit {}property delay
delay?: number;IntersectionObserver v2 - Set a minimum delay between notifications
property fallbackInView
fallbackInView?: boolean;Fallback to this inView state if the IntersectionObserver is unsupported, and a polyfill wasn't loaded
property initialInView
initialInView?: boolean;Set the initial value of the
inViewboolean. This can be used if you expect the element to be in the viewport to start with, and you want to trigger something when it leaves.
property onChange
onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void;Call this function whenever the in view state changes
property root
root?: Element | Document | null;The IntersectionObserver interface's read-only
rootproperty identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If therootis null, then the bounds of the actual document viewport are used.
property rootMargin
rootMargin?: string;Margin around the root. Can have values similar to the CSS margin property, e.g.
10px 20px 30px 40px(top, right, bottom, left).
property skip
skip?: boolean;Skip assigning the observer to the
ref
property threshold
threshold?: number | number[];Number between
0and1indicating the percentage that should be visible before triggering. Can also be anarrayof numbers, to create multiple trigger points.
property trackVisibility
trackVisibility?: boolean;IntersectionObserver v2 - Track the actual visibility of the element
property triggerOnce
triggerOnce?: boolean;Only trigger the inView callback once
Type Aliases
type IntersectionChangeEffect
type IntersectionChangeEffect<TElement extends Element = Element> = ( inView: boolean, entry: IntersectionObserverEntry & { target: TElement; }) => void;type IntersectionEffectOptions
type IntersectionEffectOptions = Omit< IntersectionOptions, 'onChange' | 'fallbackInView' | 'initialInView'>;type InViewHookResponse
type InViewHookResponse = [ (node?: Element | null) => void, boolean, IntersectionObserverEntry | undefined] & { ref: (node?: Element | null) => void; inView: boolean; entry?: IntersectionObserverEntry;};The Hook response supports both array and object destructing
type ObserverInstanceCallback
type ObserverInstanceCallback = ( inView: boolean, entry: IntersectionObserverEntry) => void;type PlainChildrenProps
type PlainChildrenProps = IntersectionOptions & { children?: React.ReactNode; /** * Render the wrapping element as this element. * This needs to be an intrinsic element. * If you want to use a custom element, please use the useInView * hook to manage the ref explicitly. * @default `'div'` */ as?: React.ElementType; /** Call this function whenever the in view state changes */ onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void;} & Omit<React.HTMLProps<HTMLElement>, 'onChange'>;Types specific to the PlainChildren rendering of InView
Package Files (1)
Dependencies (0)
No dependencies.
Dev Dependencies (24)
- @arethetypeswrong/cli
- @biomejs/biome
- @size-limit/preset-small-lib
- @testing-library/jest-dom
- @testing-library/react
- @types/node
- @types/react
- @types/react-dom
- @vitejs/plugin-react
- @vitest/browser-playwright
- @vitest/coverage-istanbul
- bumpp
- lint-staged
- microbundle
- npm-run-all
- playwright
- publint
- react
- react-dom
- simple-git-hooks
- size-limit
- tsup
- typescript
- vitest
Peer Dependencies (2)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/react-intersection-observer.
- Markdown[](https://www.jsdocs.io/package/react-intersection-observer)
- HTML<a href="https://www.jsdocs.io/package/react-intersection-observer"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3908 ms. - Missing or incorrect documentation? Open an issue for this package.
