Component Visibility Detector For React

Just another visibility detector that uses IntersectionObserver API to notify you when an element enters or exits the viewport.

Good for infinite scroll, image lazy load, scroll animation, and much more.

How to use it:

1. Install and import the Visibility Detector.

# Yarn
$ yarn add react-visibility-detector

# NPM
$ npm i react-visibility-detector --save
import VisibilityDetector from 'react-visibility-detector';

2. Handle the visible change in your app.

function handleVisibilityChange ({ visible, directionX, directionY }) {
  console.log('Element is now %s', visible ? 'visible' : 'hidden');
  console.log('Horizontal direction %s', directionX); // left, right, or none if no changed or initial
  console.log('Vertical direction %s', directionY); // up, down or none if no changed or initial
}
function MyComponent (props) {
  return (
    <VisibilityDetector onVisibilityChange={handleVisibilityChange}>
      <div>...content goes here...</div>
    </VisibilityDetector>
  );
}

3. You can also use it as a Hook.

import { useChangeVisibility } from 'react-visibility-detector';
function onVisibilityChange ({ visible, directionX, directionY }) {
  console.log('Element is now %s', visible ? 'visible' : 'hidden');
  console.log('Horizontal direction %s', directionX); // left, right, or none if no changed or initial
  console.log('Vertical direction %s', directionY); // up, down or none if no changed or initial
}
function MyComponent (props) {
  const targetRef = useRef(null);
  useChangeVisibility({ targetRef, onVisibilityChange });
  return (
    <div ref={targetRef}>...content goes here...</div>
  );
}

Preview:

Component Visibility Detector For React

Download Details:

Author: behuamuh

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/behuamuh/react-visibility-detector

License: MIT

You Might Be Interested In:

Add Comment