Giter Club home page Giter Club logo

react-intersection-observer-hook's Introduction

react-intersection-observer-hook

Build status License Version

This is a small React hook package to use Insersection Observer declaratively. By using this hook, you can easily track if a component is visible or not, create lazy loading images, trigger animations on entering or leaving the screen etc.

This package is written in TypeScript (all thanks to TSDX). So, you can use it in your TypeScript projects too.

Live demo is here.

You can check the browser compatibility from here.

If you want to support the browsers those are not supporting it natively, you can use this polyfill.

Installation

npm install react-intersection-observer-hook

Usage

Here is a simple code to use the hook. Just pass the ref callback to the component that you want to track its visibility. You can find a more complete code in the example folder.

import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
// ...

function Example() {
  // `useIntersectionObserver` returns a tuple.
  // We need to give this `ref` callback to the node we want to observe.
  // The second item, `entry` is the response of the initially created `IntersectionObserver` instance.
  const [ref, { entry }] = useIntersectionObserver();
  const isVisible = entry && entry.isIntersecting;

  useEffect(() => {
    console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
  }, [isVisible]);

  return <SomeComponentToTrack ref={ref} />;
}

if you have a scrollable container, you can set a root like this:

import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
// ...

function Example() {
  const [ref, { entry, rootRef }] = useIntersectionObserver();
  const isVisible = entry && entry.isIntersecting;

  useEffect(() => {
    console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
  }, [isVisible]);

  return (
    <ScrollableContainer
      // We use `rootRef` callback to set our root node.
      ref={rootRef}
    >
      <SomeComponentToTrack ref={ref} />
    </ScrollableContainer>
  );
}

If you just want to track visibility, you can use useTrackVisibility hook. It has the same API as useIntersectionObserver hook. It just returns additional fields in its second tuple item.

import React, { useEffect } from 'react';
import { useTrackVisibility } from 'react-intersection-observer-hook';
// ...

function Example() {
  // `useTrackVisibility` also returns a tuple like `useIntersectionObserver`.
  // First item is the same `ref` callback to set the node to observe.
  // Second item is an object that we can use to decide if a node is visible.
  // `entry`: Same object which is returned by `useIntersectionObserver`.
  // `rootRef`: Same ref callback which is returned by `useIntersectionObserver`.
  // `isVisible`: Becomes true/false based on the response of `IntersectionObserver`.
  // `wasEverVisible`: When our observed node becomes visible once, this flag becomes `true` and stays like that.
  const [
    ref,
    { entry, rootRef, isVisible, wasEverVisible },
  ] = useTrackVisibility();

  useEffect(() => {
    console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
  }, [isVisible]);

  return <SomeComponentToTrack ref={ref} />;
}

Arguments

Both useIntersectionObserver and useTrackVisibility gets the same arguments. And those are;

  • rootMargin: Indicates the margin value around the root element. Default value is zero for all directions (top, right, bottom and left).
  • threshold: Threshold value (or values) to trigger the observer.

For more info, you can check here and here.

react-intersection-observer-hook's People

Contributors

onderonur avatar dependabot[bot] avatar

Stargazers

Roman avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.