react-intersection-visible-hook

1.4.2 • Public • Published

react-intersection-visible-hook

React hook to track the visibility of a functional component based on IntersectionVisible Observer.

In the following example we changed the background color of the body depending on the visibility of the blue box.

Demo and tests are coming

import useVisibility from 'react-intersection-visible-hook'

How to use it

function App() {
  const nodeRef = useRef(null);
  const visibility = useVisibility(nodeRef);
 
  return (
    <div className="App" ref={nodeRef}>
      <h1>Hello</h1>
    </div>
  );
}
With options
const options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}
 
function App() {
  const nodeRef = useRef(null);
  const visibility = useVisibility(nodeRef, options);
 
  return (
    <div className="App" ref={nodeRef}>
      <h1>Hello</h1>
      <h2>{visibility.isIntersecting ?  'Component is visible' : 'Component is hidden' }</h2>
    </div>
  );
}

The visibility object contains

boundingClientRect
intersectionRatio
intersectionRect
isIntersecting
rootBounds
target
time

Contribute

Any pull-request is more than welcome 💥 😄

License

MIT

Package Sidebar

Install

npm i react-intersection-visible-hook

Weekly Downloads

25

Version

1.4.2

License

MIT

Unpacked Size

8.9 kB

Total Files

7

Last publish

Collaborators

  • avrmav