Element Visibility Detector In React – Visibility

A React component/hook that uses the Intersection Observer API to detect when an element is becoming visible or hidden on the page.

How to use it:

1. Install the Visibility library with NPM.

# NPM
$ npm i reactjs-visibility --save

2. Detect the visibility of an element with <VisibilityObserver> component.

import { VisibilityObserver } from "reactjs-visibility";
onst App = () => {
  const handleChangeVisibility = (visible) => {
    if (visible) {
      alert("I am now visible");
    }
  };
  const options = {
    // IntersectionObserver API options
  };
  return (
    <div>
      <VisibilityObserver
        onChangeVisibility={handleChangeVisibility}
        options={options}
      >
        ...
      </VisibilityObserver>
    </div>
  );
};

3. Detect the visibility of an element with <useVisibilityObserver> hook.

import { useVisibility } from "reactjs-visibility";
const App = () => {
  const handleChangeVisibility = (visible) => {
    if (visible) {
      alert("I am now visible");
    }
  };
  const options = {};
  const { ref, visible } = useVisibility({
    onChangeVisibility: handleChangeVisibility,
    options,
  });
  console.log(visible);
  return (
    <div>
      <div ref={ref}>Loadmore...</div>
    </div>
  );
};

Download Details:

Author: kingRayhan

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/kingRayhan/reactjs-visibility

License: MIT

You Might Be Interested In:

Add Comment