Skip to main content

useElementVisibility

React Element Hooks that tracks the visibility of an element within the viewport. A wrapper of useIntersectionObserver

Usage

Live Editor

function Demo() {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, stop] = useElementVisibility(ref);

  return (
    <div>
      <p>Info on the right bottom corner</p>
      <div
        ref={ref}
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
        }}
      >
        Target Element (scroll down)
      </div>
      <button
        onClick={() => {
          stop();
        }}
      >
        Stop
      </button>
      <div
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
          position: "fixed",
          bottom: 0,
          right: 0,
          zIndex: 100,
        }}
      >
        Element {visible ? "inside" : "outside"} the viewport
      </div>
    </div>
  );
};

Result
Loading...

API

useElementVisibility

Returns

readonly [boolean, () => void]: A tuple with the following elements:

  • is the current element visible.
  • stop observer listening function.

Arguments

ArgumentDescriptionTypeDefaultValue
targetdom elementBasicTarget<HTMLElement | SVGElement> (Required)-
optionsoptions passed to intersectionObserverIntersectionObserverInit | undefined-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;