npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@yongdamsh/use-element-visibility

v0.2.2

Published

IntersectionObserver + React Hooks

Downloads

4

Readme

useElementVisibility

IntersectionObserver API + React Hooks

NPM

Installation

NPM

To install the latest version,

npm install --save @yongdamsh/use-element-visibility

CDN

Add this script after the React and ReactDOM script tags.

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@yongdamsh/use-element-visibility"></script>

Usage

Step.1 Initialize with Options

Initialize the hook by passing the same option as IntersectionObserver.

import useElementVisibility from '@yongdamsh/use-element-visibility'

function SomeComponent() {
  // If there is no option, the following default values are applied.
  const options = {
    root: null,
    rootMargin: '0px',
    threshold: 0.0
  }

  const [visibility, subscribe, unsubscribe] = useElementVisibility(options)

  return (
    // Refer to Step.2
  )
}

Step.2 Use the visibility information and subscription-related functions

useElementVisibility hook returns the following items as an array:

visibility

Intersection information of the same specification as IntersectionObserverEntry

Example:

{
  boundingClientRect: {
    bottom: 1788.875,
    height: 836,
    left: 0,
    right: 455,
    top: 952.875,
    width: 455,
    x: 0,
    y: 952.875
  },
  intersectionRatio: 0.0,
  intersectionRect: {
    bottom: 0,
    height: 0,
    left: 0,
    right: 0,
    top: 0,
    width: 0,
    x: 0,
    y: 0
  },
  isIntersecting: false,
  isVisible: false,
  rootBounds: {
    bottom: 836,
    height: 836,
    left: 0,
    right: 455,
    top: 0,
    width: 455,
    x: 0,
    y: 0
  },
  target: Element, // https://developer.mozilla.org/ko/docs/Web/API/Element
  time: 6562.770000004093
}

subscribe

A function for subscribing to intersection information. Use the same as ref for the target node.

function SomeComponent() {
  const [visibility, subscribe, unsubscribe] = useElementVisibility()

  return (
    <main>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
      <footer id="bottom-observer" ref={subscribe}>When this area is visible, load the list further.</footer>
    </main>
  )
}

You can also subscribe multiple nodes by using multiple option as below,

function SomeComponent() {
  const [visibilities, subscribe, unsubscribe] = useElementVisibility({ multiple: true })

  // visibilities is an array of IntersectionObserverEntry
  // so you can find each visibility by element ID
  const visibilityOfItem1 = visibilities.find(v => v.target.id === 'item1');
  const visibilityOfItem2 = visibilities.find(v => v.target.id === 'item2');
  const visibilityOfItem3 = visibilities.find(v => v.target.id === 'item3');

  return (
    <main>
      <ul>
        <li id="item1" ref={subscribe}>Item 1</li>
        <li id="item2" ref={subscribe}>Item 2</li>
        <li id="item3" ref={subscribe}>Item 3</li>
      </ul>
      <pre>
        Intersection ratio of item 1: ${visibilityOfItem1 && visibilityOfItem1.intersectionRatio}
        Intersection ratio of item 2: ${visibilityOfItem2 && visibilityOfItem2.intersectionRatio}
        Intersection ratio of item 3: ${visibilityOfItem3 && visibilityOfItem3.intersectionRatio}
      </pre>
    </main>
  )
}

Note that the id attribute must be exist.

unsubscribe

A function to cancel subscription. This is useful if you need only until the node is exposed on the screen.

function SomeComponent() {
  const [visibility, subscribe, unsubscribe] = useElementVisibility()

  useEffect(() => {
    if (visibility.isIntersecting) {
      unsubscribe();

      // Process lazy loading
      const lazyImage = visibility.target;
      lazyImage.src = lazyImage.dataset.src;
    }
  }, [visibility])

  return (
    <img ref={subscribe} data-src="https://example.com/foo.jpg" />
  )
}

You can unsubscribe a specific node as shown below.

function SomeComponent() {
  const [visibilities, subscribe, unsubscribe] = useElementVisibility({ multiple: true });

  useEffect(() => {
    const intersectingEntries = visibilities.filter(v => v.isIntersecting);

    intersectingEntries.forEach(entry => {
      const lazyImage = entry.target;
      lazyImage.src = lazyImage.dataset.src;

      // Pass the element's id
      unsubscribe(lazyImage.id);
    });
  }, [visibilities]);

  return (
    <>
      <img id="img1" ref={subscribe} data-src="https://example.com/foo.jpg" />
      <img id="img2" ref={subscribe} data-src="https://example.com/foo.jpg" />
      <img id="img3" ref={subscribe} data-src="https://example.com/foo.jpg" />
    </>
  )
}

Examples

Run the command below before looking at the example,

npm run build

Then run below examples in your browser.

Browser Support

Modern browsers and IE9+

References:

  • IntersectionObserver with polyfill: https://github.com/w3c/IntersectionObserver/tree/master/polyfill#browser-support
  • React with polyfill: https://reactjs.org/docs/react-dom.html#browser-support