Nightingale Posing Mischievously

    @utilityjs/use-is-in-viewport
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.0 • Public • Published

    useIsInViewport

    A React hook that tells you when an element enters or leaves the viewport.
    (Reuses observer instances where possible)

    license npm latest package npm downloads types

    npm i @utilityjs/use-is-in-viewport | yarn add @utilityjs/use-is-in-viewport

    Usage

    const App: React.FC = () => {
      const { registerNode, isInViewport } = useIsInViewport();
    
      console.log(`is red box in the viewport? ${isInViewport}`);
    
      return (
        <div className="app">
          <div style={{ height: 300,backgroundColor: "black" }}></div>
          <div style={{ height: 300,backgroundColor: "black" }}></div>
          <div style={{ height: 300,backgroundColor: "black" }}></div>
          <div
            ref={registerNode}
            style={{
              height: 300,
              backgroundColor: "red"
            }}
          ></div>
          <div style={{ height: 300,backgroundColor: "black" }}></div>
          <div style={{ height: 300,backgroundColor: "black" }}></div>
        </div>
      );
    };

    API

    useIsInViewport( options?)

    interface HookOptions {
      once?: boolean;
      disabled?: boolean;
    }
    
    interface HookConsumer {
      registerNode: <T extends HTMLElement>(node: T | null) => void;
      isInViewport: boolean;
    }
    
    declare const useIsInViewport: (
      options?: (IntersectionObserverInit & HookOptions) | undefined
    ) => HookConsumer;

    options.once - (default: false)

    Only trigger the callback once. (unless you have toggled disabled option.)

    options.disabled - (default: false)

    Skip creating the observer.
    You can use this to enable and disable the observer as needed.

    options.threshold - (default: [0, 1])

    Read the MDN Web Doc

    options.root - (default: null)

    Read the MDN Web Doc

    options.rootMargin - (default: 0px)

    Read the MDN Web Doc

    Install

    npm i @utilityjs/use-is-in-viewport

    DownloadsWeekly Downloads

    3

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    15.9 kB

    Total Files

    8

    Last publish

    Collaborators

    • mimshins