react-intersection-observer

  • Version 9.14.1
  • Published
  • 129 kB
  • No dependencies
  • MIT license

Install

npm i react-intersection-observer
yarn add react-intersection-observer
pnpm add react-intersection-observer

Overview

Monitor if a component is inside the viewport, using IntersectionObserver API

Index

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 - true or false: Set the inView value 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 inView state of your components. Call the useInView hook with the (optional) [options](#options) you need. It will return an array containing a ref, the inView status and the current [entry](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry). Assign the ref to 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>
    );
    };

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 of inView. In addition to the inView prop, children also receive a ref that 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) on entry, 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 the onChange method, 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 the className, 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 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 inView boolean and ref that 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 inView boolean. 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 root property 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 the root is 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 0 and 1 indicating the percentage that should be visible before triggering. Can also be an array of 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 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 (22)

                            Peer Dependencies (2)

                            Badge

                            To add a badge like this onejsDocs.io badgeto 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
                              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](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>