Infinite scrolling with React JS

Basically when scrolling you want to decide which elements are visible and then rerender to display only those elements, with a single spacer element on top and bottom to represent the offscreen elements.

Vjeux made a fiddle here which you can look at: jsfiddle.

Upon scrolling it executes

scrollState: function(scroll) {
    var visibleStart = Math.floor(scroll / this.state.recordHeight);
    var visibleEnd = Math.min(visibleStart + this.state.recordsPerBody, this.state.total - 1);

    var displayStart = Math.max(0, Math.floor(scroll / this.state.recordHeight) - this.state.recordsPerBody * 1.5);
    var displayEnd = Math.min(displayStart + 4 * this.state.recordsPerBody, this.state.total - 1);

    this.setState({
        visibleStart: visibleStart,
        visibleEnd: visibleEnd,
        displayStart: displayStart,
        displayEnd: displayEnd,
        scroll: scroll
    });
},

and then the render function will display only the rows in the range displayStart..displayEnd.

You may also be interested in ReactJS: Modeling Bi-Directional Infinite Scrolling.


Check out our React Infinite Library:

https://github.com/seatgeek/react-infinite

Update December 2016

I've actually been using react-virtualized in a lot of my projects recently and find that it covers the majority of use cases a lot better. Both libraries are good, it depends on exactly what you're looking for. For instance, react-virtualized supports variable height JIT measuring via an HOC called CellMeasurer, example here https://bvaughn.github.io/react-virtualized/#/components/CellMeasurer.

Update November 2018

A lot of the lessons from react-virtualized have been ported to the smaller, faster, more efficient react-window library from the same author.