Infinite Scrolling/More Loading without using library in React Component

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:

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

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.

[java]
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
}
}
[/java]

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 πŸ™‚