Skip to content

olistic/react-use-visibility

Repository files navigation

react-use-visibility

React hook for tracking components visibility.

Travis Codecov

Demo

Electrons becoming excited as they enter the screen.

Installation

$ npm install --save react-use-visibility

Additionally, you'll need to install version 16.7.0-alpha.0 of react and react-dom since this package relies on React Hooks:

DISCLAIMER: React Hooks are an experimental proposal. The Hooks API, as well as this library's, are unstable and subject to change.

Usage

import React, { useRef } from 'react';
import useVisibility from 'react-use-visibility';

function Electron() {
  // Use a ref to attach to the element whose visibility you want to keep track of.
  const imgRef = useRef();

  // `current` points to the mounted img element.
  const isVisible = useVisibility(imgRef.current);

  return (
    <img
      ref={imgRef}
      src={electron}
      className={isVisible ? 'excited' : ''}
      alt="an electron"
    />
  );
}

API Reference

useVisibility

const isVisible = useVisibility(el, options);

Accepts a React element as the first argument (el) and returns whether it is on the screen or not.

Optionally, you can pass a second argument to useVisibility that is an object with the following properties:

  • partial (boolean): Whether to consider the element visible when only a part of it is on the screen. Defaults to false.
  • scrollableEl (Element): The parent element triggering the scroll event. Defaults to window.

About

React hook for tracking components visibility

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published