useInViewport

A hook that can observe whether the element is in the visible area, and the visible area ratio of the element.

const [isInViewport, ratio] = useInViewport(target);

Example

Basic usage of useInViewport hook.

Observe the visible area ratio of element target
Test scroll within viewport

The root container
target element
in viewport: visible
ratio: 1
import React, { useRef, useState } from "react";
import { useInViewport, Button, Divider } from "../../../index";
import "./index.less";

// Example FC
const Example = () => {
  const [height, setHeight] = useState("auto");
  const containerRef = useRef<HTMLDivElement>(null);
  const targetRef = useRef<HTMLDivElement>(null);

  const [isInViewport, ratio] = useInViewport(targetRef.current, {
    threshold: [0, 0.25, 0.5, 0.75, 1],
    root: containerRef.current,
  });

  const wrapStyle = {
    color: isInViewport ? "green" : "red",
  };

  return (
    <>
      <Divider contentAlign="left">
        Observe the visible area ratio of element target
      </Divider>
      <Button
        type="default"
        inline
        size="small"
        onClick={() => setHeight("500px")}
      >
        Test scroll within viewport
      </Button>
      <br />
      <br />
      <div ref={containerRef} className="viewport-example-wrapper">
        The root container
        <div style={{ height }}>
          <div ref={targetRef} className="viewport-example-target">
            target element
          </div>
        </div>
      </div>
      <Divider contentAlign="left">
        <div style={wrapStyle}>
          in viewport: {isInViewport ? "visible" : "hidden"}
        </div>
      </Divider>
      <Divider contentAlign="left">
        <div style={wrapStyle}>ratio: {ratio}</div>
      </Divider>
    </>
  );
};

export default Example;

API

| Property | Description | Type | Default | | -------- | ---------------------- | ----------------------------------------------------------- | ------- | --- | | target | The DOM element or ref | Element | () => Element | MutableRefObject<Element> | - | | | options | The config options | Options | - |

Options

PropertyDescriptionTypeDefault
thresholdEither 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[]-
rootMarginThe margin around the root.string-
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>-
ON THIS PAGE