Giter VIP home page Giter VIP logo

react-intersection-list's Introduction

React Intersection List

Build Status Codecov Greenkeeper badge NPM version styled with prettier


Agent Smith: ...we have no choice but to continue as planned. Deploy the sentinels. Immediately.

React Intersection List builds on top of React Intersection Observer, using a sentinel in the DOM to deliver a high-performance and smooth scrolling experience, even on low-end devices.

Getting Started

$ npm install --save @researchgate/react-intersection-list

And optionally the polyfill:

$ npm install --save intersection-observer

Next create a <List> and two instance methods as props children and itemRenderer:

import React from 'react';
import List from '@researchgate/react-intersection-list';

export default class MyList extends React.Component {
    itemsRenderer = (items, ref) => (
        <ul className="list" ref={ref}>
            {items}
        </ul>
    );

    itemRenderer = (index, key) => <li key={key}>{index}</li>;

    render() {
        return (
            <List currentLength={1000} itemsRenderer={this.itemsRenderer}>
                {this.itemRenderer}
            </List>
        );
    }
}

Note that <List> is a PureComponent so it can keep itself from re-rendering. It's highly recommended to pass referenced methods for children and itemsRenderer (in this case instance methods), so that it can successfully shallow compare props.

Why React Intersection List?

The approach to infinite scrolling was commonly done by devs implementing throttled scroll event callbacks. This keeps the main thread unnecessarily busy... No more! IntersectionObservers invoke callbacks in a low-priority and asynchronous way by design.

Agent Smith: Never send a human to do a machine's job.

The implementation follows these steps:

  1. Add a sentinel close to the last item in the list
  2. Update the list moving the internal cursor
  3. Trigger a callback when the sentinel comes into view
  4. Reposition the recycled sentinel at the end
  5. Repeat (โˆž) ?

Documentation

How to

Provided an itemsRenderer prop you must attach the ref argument to your scrollable DOM element:

<div ref={ref}>{items}</div>;

This element specifies overflow: auto|scroll and it'll become the IntersectionObserver root. If the overflow property isn't found, then window will be used as the root instead.

The sentinel element is by default detached from the list when the current size reaches the available length, unless you're using awaitMore. In case your list is in memory and you rely on the list for incremental rendering only, the default detaching behavior suffices. If you're loading items asynchoronously on-demand, make sure to switch awaitMore once you reach the total length.

FAQ

Q: Why am I receiving too many onIntersection callbacks

We extend React.PureComponent, so IF the parent component re-renders, and the props passed to your <List /> don't hold the same reference anymore, the list re-renders and may accidentally be re-attaching the sentinel.

Q: Do I always need to assign the ref?

Yes, this callback is used to start up the IntersectionObserver.

Q: What's the threshold value, and why does it need a unit?

The threshold value is the amount of space needed before the sentinel intersects with the root. The prop is transformed into a valid rootMargin property for the IntersectionObserver, depending on the axis you select. As a sidenote, we believe that a percentage unit works best for responsive layouts.

Q: I am getting a console warning when I first load the list

The sentinel detected a viewport with a bigger size than the size of its items...

The prop pageSize is 10 by default, so make sure you're not falling short on items when you first render the component. The idea of an infinite scrolling list is that items overflow the viewport, so that users have the impression that there're always more items available.

Q: Why doesn't the list render my updated list element(s)?

The list renders items based on its props. An update somewhere else in your app (or within your list item) might update your list element(s), but if your list's currentLength prop for instance, remains unchanged, the list prevents a re-render. Updating the entire infinite list when one of its items has changed is far from optimal. Instead, update your list items independently using internal state or something like react-redux's connect().

Q: Are you planning to implement a "virtual list mode" like react-virtualized?

Yes, there's already an open issue to implement a mode using occlusion culling.

Props

property type default description
children (index: number, key: number) => React.Element (index, key) => <div key={key}>{index}</div> render function as children;
gets call once for each item.
itemsRenderer (items: Array(React.Element), ref: HTMLElement) => React.Element (items, ref) => <div ref={ref}>{items}</div> render function for the list's
root element, often returning a scrollable element.
currentLength number 0 item count to render.
awaitMore boolean if true keeps the sentinel from detaching.
onIntersection (size: number, pageSize: number) => void invoked when the sentinel comes into view.
threshold string 100px value in absolute px or %
as spacing before the sentinel hits the edge of the list's viewport.
axis string y scroll direction: y == vertical and x == horizontal
pageSize number 10 number of items to render each hit.
initialIndex number 0 start position of iterator of items.

Examples

Find multiple examples under: https://researchgate.github.io/react-intersection-list/

Contributing

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

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.

react-intersection-list's People

Contributors

rendez avatar greenkeeper[bot] avatar danez avatar mdio avatar

Watchers

Noel Jackson avatar 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.