In the world of fast-paced technological society, Who has the time to click number of pages and its contents? People always look for shortcuts, swipes and other gestures. The efficient way to get through pages of content is the infinite scroll / more loading.

In the infinite scroll, new content is loaded as you scroll down the page. When you get the bottom of content, then web page loads new content and appends it to bottom.

A familiar example could be Facebook, you are presented with feed of posts and images. And as you scroll down, more posts showing up.

You will find many articles, blog posts, components, libraries related to infinite scrolling. While trying those in one my projects, it was giving issues, sometimes bottom was not triggering even if you are at the bottom. 🙁

So keeping in mind that, thought to write simple implementation of infinite scrolling. Hopefully that will surely help you. 🙂

So lets start and see how we can implement in React Component.

Firstly you’ll need to listen to a scroll event — something like this:

componentDidMount() {
//fetch data (api call)
window.addEventListener(‘scroll’, this.onScroll);
}

Note: Updating your state on every scroll event is probably over-kill though. The best approach would be to detect when the user has scrolled to the bottom and then conditionally load new data.

That can be handled in following way in onScroll method.

onScroll = () => {
const windowHeight = “innerHeight” in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;

if (windowBottom >= docHeight-1) {
console.log(“at the bottom”);
//fetch new data (api call)and append to existing list
} else {
console.log(“not at the bottom”);
//don’t do anything
}
}

So in above code once the bottom reach, it will trigger if condition, there you can fetch new data and append to existing list and update UI.

This is the simple way of implementing infinite scrolling / more loading in react components. 🙂

Feel free to ask for any questions 🙂

Do you have any product idea or business need?

How TO MAKE YOUR APP WORK OFFLINE

HOW TO MAKE YOUR APP WORK OFFLINE

Offline mobile app development is critical for users to sync their data properly, when offline. Here, we help you learn the process from implementation to data synchroniz

Omnivore POS integration - Ensuring Agility To Your Restaurant Businesses

Omnivore POS integration - Ensuring Agility To Your Restaurant Businesses

Omnivore software offers a point-of-sales integration API making the restaurant system agile, more customer engaging and adaptive to fast changing business environments.

Unit Testing using Mockk.io

Unit Testing using mockK.io in Kotlin

Learn about unit testing using mockk.io in Kotlin.