How to build an infinite loader component in ReactJS.
This article will help you to build a re-usable infinite loader component using ReactJS and Intersection Observer API.
Originally published on https://gulamhussain.dev
This is what we will be building. You can find all code in Github Repo
Prerequisites
- ReactJS
- Intersection Observer API
What is infinite loader?
Infinite loader is a mechanism to show data on a page based on user scroll activity. It’s a pagination mechanism but instead of clicking on a page number to navigate, the user will keep scrolling to load more data on the page.
We will be using JavaScript Intersection Observer API to check if the user has scrolled to the end of the page, and based on the threshold we will perform data fetching functions.
For dummy data we will be using JSON placeholder dummy API, it will return 10 records per page.
https://jsonplaceholder.typicode.com/photos?_limit=10&_page=1
Let’s build a simple component that loads data using dummy API and then will implement infinite loader to perform load more operation. We will be using axios
for data fetching, so first install that if you haven’t -
npm install axios
Now let’s create a PhotoLoader
component that will load photos from a dummy API. This component has getPhotos
a method which will be executed when the component mounts. This method will make an API call using axios
and save loaded data in the state. getPhotos
will also update the current page that the user is on, based on that getPhotos
will load the latest data from the server.
In PhotoLoader
we have imported ScrollLoader
component, so let’s build that —
ScrollLoader
Component should be the last component in your render function.
In the constructor, we have Initialised two variables -
this.loaderEl
this is the target element, as soon as the target element intersect the viewport we will perform a load more data operation.this.prevRatio
this will be used to record the latest visibility ratio of the element, and used to check if the target element is becoming more visible or less visible since the last intersection.
createObserver
method setup an observer for target element and setup a handleIntersect
method which will be executed on page scroll. It will check -
- If load more operation is in progress, if yes then return from the method
- If there is more data to be fetched, in our example it’s always true but in a real-world application, this will depend on the data.
- If the target element is in the viewport.
Based on these 3 conditions handleIntersect
will execute this.props.onLoad
a method which in turns makes an API call to get more data.
Conclusion
ScrollLoader
requires minimal props and isolate the intersection logic from your main component, this makes it easy to re-use throughout the application. Feel free to make any modification to make it better and if you have any query let me know.