learn react ui logoLearnReactUI
How to Build an Infinite Scroll List with React

How to Build an Infinite Scroll List with React

Infinite scrolling is a web design technique used to load content continuously as the user scrolls down a page. Instead of requiring the user to click a "Next" button or pagination link to load more content, new content automatically loads when the user reaches the bottom (or a certain threshold) of the current page.

Infinite Scrolling is proper when you don’t know the page size. Your items are in the stream (For example, timeline). And the only chance is to display items in an order. Then implementing Infinite Scrolling best way for usability. I wrote a simple simulation that loads new items when users access the last things of Scrolling. [Demo]

Demo ScreenShot

First, we need a list container that has a fixed height and overflow-y scrolling capability.

Overflow Styling

The second part is information card items and a Loading … element. Loading element only visible when fetching operations active.

Loading Element

Scrolling Mechanics

When the component mounts to the app, we add scrolling listeners to “infinite-scroll-container” and remove it when the element is unmounted.

Scrolling EventListener subscribe/unsubscribe

The essential part here is “track scrolling” what will we do in track scrolling?

  • Check you access the bottom of the scrolling area.

  • If access then fetch a new chunk of data from Backend

  • And generate new items and render them in to list container

Track scrolling Algorithm Steps

Checking Scrolling Access The Last Element

We get DOM element with the help of document.getElementById. After that, we calculate scrolling access bottom. If scroll access to bottom and to fetch false, then we started fetching operation.

if (el.offsetHeight + el.scrollTop >= el.scrollHeight)

Scroll Access To Bottom function

Then I wrote a simple fake fetching function that generates new items after waiting 0.6 second

Fake fetching function