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

@existentialism/react-intersection-observer

v0.5.0

Published

React component for the Intersection Observer API

Downloads

4

Readme

Bring ReactIntersectionObserver over today, your React children will love it!

React Intersection Observer is a React component, acting as a wrapper for the IntersectionObserver API. It is fully declarative and takes care of all the imperative parts for you.

React Intersection Observer is good at:

  • reusing instances: comparing the passed options
  • performance: chooses smartly when to re-render and when to re-observe
  • being unopinionated: how to handle visibility changes is left entirely up to the developer
  • being intuitive: looks like the Native API

What does IntersectionObserver do?

IntersectionObservers calculate how much of a target element overlaps (or "intersects with") the visible portion of a page, also known as the browser's "viewport":

- Dan Callahan · 

Graphic example

Getting started

npm install --save @researchgate/react-intersection-observer

Optionally add the polyfill and make sure it's required on your dependendencies for unsupporting browsers:

npm install --save intersection-observer

Usage:

import React from 'react';
import 'intersection-observer'; // optional polyfill
import Observer from '@researchgate/react-intersection-observer';

class ExampleComponent extends React.Component {
    handleIntersection(event) {
        console.log(event.isIntersecting);
    }

    render() {
        const options = {
            onChange: this.handleIntersection,
            root: "#scrolling-container",
            rootMargin: "0% 0% -25%"
        };

        return (
            <div id="scrolling-container" style={{ overflow: 'scroll', height: 100 }}>
                <Observer {...options}>
                    <div>
                        I am the target element
                    </div>
                </Observer>
            </div>
        );
    }
}

Why ReactIntersectionObserver?

The motivation is to provide the easiest possible solution for observing elements that enter the viewport on your React codebase. It's fully declarative and all complexity is abstracted away, focusing on reusability, and low memory consumption.

No bookkeeping

It's built with compatibility in mind, adhering 100% to the native API implementation and DSL, but takes care of all the bookkeeping work for you.

Instances and nodes are managed internally so that any changes to the passed options or tree root reconciliation cleans up and re-observes nodes on-demand to avoid any unexpected memory leaks.

No extra markup

ReactIntersectionObserver does not create any extra DOM elements, it attaches to the only child you'll provide to it. Internally it warns you if attaching a ref to it fails - common mistake when using a stateless component in React 15 - and will invoke any existing ref callback upon the passed child element.

Easy to adopt

When using ReactIntersectionObserver the only required prop is the onChange function. Any changes to the visibility of the element will invoke this callback, just like in the native API - you’ll receive one IntersectionObserverEntry argument per change. This gives you an ideal and flexible base to build upon.

Some of the things you may want to use ReactIntersectionObserver for:

Documentation

Demos

Find multiple examples and usage guidelines under: https://researchgate.github.io/react-intersection-observer/

demo

Recipes

Recipes are useful code snippets solutions to common problems, for example, how to use ReactIntersectionObserver within a Higher Order Component.

Discover more recipes in our examples section.

Options

root: HTMLElement|string | default window object

The element or selector string that is used as the viewport for checking visibility of the target.

rootMargin: string | default 0px 0px 0px 0px

Margin around the root. Specify using units px or % (top, right, bottom left). Can contain negative values.

threshold: number|Array<number> | default: 0

Indicates at what percentage of the target's visibility the observer's callback should be executed. If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. If you want the callback run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1].

onlyOnce: boolean | default: false

When true indicate that events fire only until the element is intersecting. Requires IntersectionObserverEntry's object to contain isIntersecting in its prototype.

disabled: boolean | default: false

Controls whether the element should stop being observed by its IntersectionObserver instance. Useful for temporarily disabling the observing mechanism and restoring it later.

onChange (required): (entry: IntersectionObserverEntry) => void

Function that will be invoked whenever an observer's callback contains this target in its changes.

children (required): React.Element<*>

Single React component or element that is used as the target (observable).

Notes

  • According to the spec, an initial event is being fired when starting to observe a non-intersecting element as well.
  • Changes happen asynchronously, similar to the way requestIdleCallback works.
  • Although you can consider callbacks immediate - always below 1 second - you can also get an immediate response on an element's visibility with observer.takeRecords().
  • The primitives Map, Set, and Symbol are required and won't be transpiled by default. Consider using a polyfill for browsers lacking ES2015 support. If you're using babel, include "babel-polyfill" somewhere to your codebase.

Polyfill

When needing the full spec's support, we highly recommend using the IntersectionObserver polyfill.

Caveats

Ealier Spec

Earlier preview versions of Edge and prior to version 58 of Chrome, the support for isIntersecting was lacking. This property was added to the spec later and both teams where unable to implement it earlier.

If you are using the prop onlyOnce or you need this field within your IntersectionObserverEntry instances, make sure to require the version ^0.4.0.

Performance issues

As the above-mentioned polyfill doesn't perform callback invocation asynchronously, you might want to decorate your onChange callback with a requestIdleCallback or setTimeout call to avoid a potential performance degradation:

onChange = (entry) => requestIdleCallback(() => this.handleChange(entry));

IntersectionObserver's Browser Support

Out of the box

  • [1] Reportedly available, it didn't trigger the events on initial load and lacks isIntersecting until later versions.
  • [2] This feature was implemented in Gecko 53.0 (Firefox 53.0 / Thunderbird 53.0 / SeaMonkey 2.50) behind the preference dom.IntersectionObserver.enabled.

Using polyfill

Contributing

We'd love your help on creating React Intersection Observer!

Before you do, please read our Code of Conduct so you know what we expect when you contribute to our projects.

Our Contributing Guide tells you about our development process and what we're looking for, gives you instructions on how to issue bugs and suggest features, and explains how you can build and test your changes.

Haven't contributed to an open source project before? No problem! Contributing Guide has you covered as well.