How to Add Infinite Scroll in React.js
React.js is one of the most popular JavaScript libraries for building frontend web applications. One of the most common problems developers face when building large-scale applications is the performance issues of showing large amounts of data to users. A great solution to this problem is adding infinite scroll to your React application. In this tutorial, we will learn how to add infinite scroll in React.js.
What is Infinite Scroll?
Infinite Scroll is a web design technique that loads a certain number of content based on the scroll event. It is different from pagination where the user clicks on a button to navigate to another set of content. Instead, infinite scroll loads more content automatically as the user scrolls down the page.
Step 1: Create a React Component
The first step is to create a React component that displays the initial set of data. In our example, we will create a simple component that displays a list of photos.
“`
import React, { useState } from ‘react’;
function App() {
const [photos, setPhotos] = useState([
{
id: 1,
src: ‘https://via.placeholder.com/150’
},
{
id: 2,
src: ‘https://via.placeholder.com/150’
},
{
id: 3,
src: ‘https://via.placeholder.com/150’
},
{
id: 4,
src: ‘https://via.placeholder.com/150’
}
]);
return (
Infinite Scroll
{photos.map(photo => (
))}
);
}
export default App;
“`
Step 2: Add Intersection Observer API
Next, we need to add the Intersection Observer API that allows us to create a function that will check if the user has scrolled to the end of the page. If the user has reached the end of the page, we will fetch more data from the server and append it to the existing data.
“`
import React, { useState, useEffect, useRef } from ‘react’;
function App() {
const [photos, setPhotos] = useState([
{
id: 1,
src: ‘https://via.placeholder.com/150’
},
{
id: 2,
src: ‘https://via.placeholder.com/150’
},
{
id: 3,
src: ‘https://via.placeholder.com/150’
},
{
id: 4,
src: ‘https://via.placeholder.com/150’
}
]);
const [pageNumber, setPageNumber] = useState(1);
const loadMoreRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
entries => {
const firstEntry = entries[0];
if (firstEntry.isIntersecting) {
setPageNumber(prevPageNumber => prevPageNumber + 1);
}
},
{
root: null,
rootMargin: ‘0px’,
threshold: 1.0
}
);
if (loadMoreRef.current) {
observer.observe(loadMoreRef.current);
}
return () => {
if (loadMoreRef.current) {
observer.unobserve(loadMoreRef.current);
}
};
}, []);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/photos?_page=${pageNumber}&_limit=4`)
.then(response => response.json())
.then(newPhotos => {
setPhotos(prevPhotos => […prevPhotos, …newPhotos]);
});
}, [pageNumber]);
return (
Infinite Scroll
{photos.map(photo => (
))}
);
}
export default App;
“`
In the code above, we added a new state variable called `pageNumber` that keeps track of the page number. We also added a `loadMoreRef` that will be used to check if the user has scrolled to the end of the page.
In the `useEffect` hook, we created an instance of the `IntersectionObserver` API and observed the `loadMoreRef`. If the `loadMoreRef` is intersecting with the viewport, we will increment the `pageNumber`. When the `pageNumber` is changed, a new API request is sent to the server to fetch more data. The new data is then appended to the existing data using the `setPhotos` function.
Finally, we added a new `li` element with the `loadMoreRef` as a reference. This is used to detect when the user has reached the bottom of the page.