Skip to content

Latest commit

 

History

History
67 lines (51 loc) · 2.04 KB

useViewportSpy.md

File metadata and controls

67 lines (51 loc) · 2.04 KB

useViewportSpy

Uses the IntersectionObserver API to tell whether the given DOM Element (from useRef) is visible within the viewport.

Why? 💡

  • Asynchronously observes changes in the intersection of the given element with the document
  • Can be used to perform animation when the component appear within the viewport

Basic Usage:

import { useRef } from 'react'; 
import { useViewportSpy } from 'beautiful-react-hooks'; 

const ViewportSpyComponent = () => {
   const ref = useRef();
   const isVisible = useViewportSpy(ref);
      
   return (
     <DisplayDemo>
       <div ref={ref} style={{padding: '20px 0', background: '#1D6C8B'}}>
          Observed element
       </div>
       <div style={{margin: '20px 0'}}>
         is the observed element in viewport? {isVisible ? 'yes': 'no'}
       </div>
     </DisplayDemo>
   );
};

<ViewportSpyComponent />

Options

The second argument could possibly be an object of IntersectionObserver options

import { useRef } from 'react'; 
import { useViewportSpy } from 'beautiful-react-hooks'; 

const ViewportSpyComponent = () => {
   const ref = useRef();
   const isVisible = useViewportSpy(ref, { threshold: 0.6 });
      
   return (
     <DisplayDemo>
       <div ref={ref} style={{padding: '20px 0', background: '#1D6C8B'}}>
          Observed element
       </div>
       <div style={{margin: '20px 0'}}>
         is the observed element in viewport? {isVisible ? 'yes': 'no'}
       </div>
     </DisplayDemo>
   );
};

<ViewportSpyComponent />

✅ Pro tip:

This hook can be used to perform animations when a component/element enters or exit the viewport. To deeply understand IntersectionObserver please read Using the Intersection Observer API to Trigger Animations and Transitions