• Stars
    star
    141
  • Rank 259,971 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React infinite scroll using the Intersection <Observer /> API

โš ๏ธ This repository is not as actively maintained as we wish it to be. Feel free to fork this project and fix any outstanding issues you might have, and we'll try to merge relevant changes eventually. We apologize for the inconvenience.

React Intersection List

Build Status Codecov 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.


Table of Contents

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, { Component } from 'react';
import List from '@researchgate/react-intersection-list';

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

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

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

Note that <List> is a PureComponent so it can keep itself from re-rendering. It's highly recommended to avoid creating new functions for renderItem and itemsRenderer so that it can successfully shallow compare props on re-render.

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 more items in an asynchoronous way, make sure you switch awaitMore once you reach the total length (bottom of the list).

The prop itemCount must be used if the prop items is not provided, and viceversa. Calculating the list size is done by adding the current size and the page size until the items' length is reached.

FAQ

Why am I receiving too many `onIntersection` callbacks We extend `PureComponent`. That means, if the parent component re-renders and the _props_ passed to your `` don't hold the same reference anymore, the list re-renders and we accidentally restart the `IntersectionObserver` of the `Sentinel`.

Do I always need to assign the `ref`? Yes, the ref callback will be used as the `root` and is forwarded to the `IntersectionObserver` within the `Sentinel`.

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.

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.

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 each item individually with some form of `connect()` function or observables.

Are you planning to implement a "virtual list mode" like react-virtualized? Yes, there's already an [open issue](#2) to implement a mode using occlusion culling. It will be implemented in a future release. If you can't wait, you could help us out by opening a Pull Request :)

Props

property type default description
renderItem/children (index: number, key: number) => React.Element (index, key) => <div key={key}>{index}</div> render function as children or render props;
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.
itemCount/items number/Array (or Iterable Object) 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.

More Repositories

1

react-intersection-observer

React component for the Intersection <Observer /> API
JavaScript
1,125
star
2

gradle-release

gradle-release is a plugin for providing a Maven-like release process for projects using Gradle
Groovy
865
star
3

broker

A full proxy for composer repositories
PHP
119
star
4

webpack-watchman-plugin

A webpack plugin that integrates watchman as its watcher.
JavaScript
55
star
5

phpnsc

Small tool to check for missing use statements when using PHP namespaces
PHP
43
star
6

react-fast-highlight

A fast react component wrapper for highlight.js
TypeScript
40
star
7

injektor

Dependency injection container for PHP, inspired by google-guice
PHP
38
star
8

avro-php

Generic Apache Avro PHP available as a composer package
PHP
38
star
9

azkaban-ldap-usermanager

Ldap authentication for Azkaban
Java
24
star
10

path-chunk-webpack-plugin

[Deprecated] Plugin to create a chunk based on matching against the module path.
JavaScript
22
star
11

spire

๐Ÿ—ผExtensible JavaScript toolbox management
JavaScript
22
star
12

gemini-react

Plugin, which simplifies writing gemini tests for react components
JavaScript
22
star
13

inline-stylesheet

Create inline styles for your components
JavaScript
21
star
14

restler

Restler is a project aiming on providing a unified way to easily build REST-services based on document-oriented databases, like MongoDB.
Java
16
star
15

moment-shortformat

moment-shortformat.js is an extension to moment.js that formats dates in a short format like it's used on ResearchGate.
JavaScript
16
star
16

gradle-release-examples

Repository containing all kinds of different configuration possibilities for the gradle-release plugin
Java
12
star
17

node-file-processor

Node.js utility for mass-processing files in parallel.
JavaScript
10
star
18

grunt-changed

Configure Grunt tasks to run with changed file contents only
JavaScript
10
star
19

babel-plugin-transform-scss-import-to-string

Babel plugin for inlining Sass imports into transpiled strings
JavaScript
10
star
20

babel-plugin-react-class-display-name

Add displayName to ES6 classes that extend React.Component
JavaScript
9
star
21

emailonacid

โœ‰๏ธ Mail visual regression testing library based on Email on Acid API
JavaScript
8
star
22

tooling

๐Ÿ›  ResearchGate's JavaScript Tooling
JavaScript
7
star
23

node-package-blueprint

Blueprint for scaffolding new node packages
JavaScript
7
star
24

rosalind-serif

Rosalind Serif โ€“ย A serif typeface built for ResearchGate
7
star
25

nodejs-simple-downloader

A simple cli downloader for nodejs
Go
5
star
26

mongoose-avro-schema-generator

Generates Apache avro schemas from mongoose schemas.
JavaScript
5
star
27

archaius-consul

Consul Connector for Archaius
Java
5
star
28

typewriter

PHP
4
star
29

CodingDojo

CodingDojo for Berlin organized at ResearchGate
Python
4
star
30

kafka-metamorph

Apache Kafka consumer API for selective partition consumption and explicit offset control
Java
3
star
31

doctrine-file

File-Reader for the Doctrine JSDoc Parser
JavaScript
3
star
32

foreman-templates

HTML
2
star
33

babel-preset-rg

Moved to https://github.com/researchgate/tooling
JavaScript
2
star
34

linting

Moved to https://github.com/researchgate/tooling
JavaScript
2
star
35

gemini-babel

Gemini plugin, which allows to use babel for writing tests.
JavaScript
2
star
36

babel-plugin-transform-react-jsx-props

Add additional props to a jsx snippet
JavaScript
1
star
37

gemini-localip

Gemini plugin to dynamically set root url to local ip address
JavaScript
1
star
38

diamond-linkerd-collector

Python
1
star
39

webpack-plugin-flow

Runs flow check before webpack compile or watch
JavaScript
1
star
40

logstash_gelfamqp_plugin

A logstash output plugin converts a logstash message to a GELF message that can be consumed by graylog2 and then pushes them to an amqp exchange.
Ruby
1
star