Understanding Infinite scroll techniques in React Js

Introduction

Infinite scrolling is a web design technique that loads content continuously as the user scrolls down the page, eliminating the need for pagination.

Content is often loaded asynchronously by making a request to the server. Often times this can improve the user experience on a website.

But not always. Sometimes it’s terrible.

Infinite scrolling technically requires adding a scroll event listener to the window object or a certain div. This determines when the scroll has reached the bottom of the div and then performs actions accordingly.

In this tutorial, I will explain two methods of implementing infinite scroll in React:

The first method describes implementing everything from the ground up

The second method uses an already available infinite scroll library/component

A basic understanding of React is needed to follow through this tutorial.

Implementing from the ground up

As mentioned earlier, infinite scroll is about attaching event listeners to DOM elements while watching for when the scrollbar hits the bottom of the div.

What you have is a normal component that shows a couple li‘s showing the items number. How do you add infinite scroll to this component? remember the ref called myscroll? You get to use it now. Define theComponentWillMount method:

In the method above, a scroll listener was added to the myscroll ref which references the div being targeted. Here you used the scrollTop property of the element to get the scroll position (which is relative to the top of the window) and then added it to the clientHeight property (the height of the document).

Next, a check is made to see if the sum of those two properties is greater than or equal to the height of the scrollbar. If the assumption is true, then the bottom of the div has been reached. A new function called loadMore (Which will be created next) is then fired.