Skip to content

React hook for tracking component viewability, based on IntersectionObserver

License

Notifications You must be signed in to change notification settings

jamonserrano/react-use-viewability

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 

Repository files navigation

react-use-viewability

React hook for tracking component viewability, based on IntersectionObserver.

Installation

$ npm install react-use-viewability --save-dev

Usage

The hook accepts the standard IntersectionObserver options and returns an array containing an inView value that always reflects the component's viewability, and an inViewRef ref that must be passed to the element you want to track.

Example (try the live version):

import React from 'react';
import useViewability from 'react-use-viewability';

const Box = props => {
  // Consider the element viewable when at least half of it is in the viewport
  const [inView, inViewRef] = useViewability({ threshold: 0.5 });

  return (
    <div
      // Pass the received ref to the element
      ref={inViewRef}
      // Change background color when entering or leaving the viewport
      style={{ backgroundColor: inView ? 'green' : 'red' }}
    />
  );
};

export default Box;

License

MIT License

About

React hook for tracking component viewability, based on IntersectionObserver

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published