Creating a paginated infinite scroll in a React.js app involves fetching paginated data from an API and dynamically loading more data as the user scrolls down the page. Here's a basic example of how to implement this:
Set Up Your Project:
Create a new React.js app or use an existing one.
Fetch Paginated Data:
Create a function to fetch paginated data from your API. You can use fetch
or any HTTP library like Axios.
javascriptasync function fetchData(page) {
const response = await fetch(`https://api.example.com/data?page=${page}`);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return response.json();
}
Create a Component for Infinite Scroll:
Create a component named InfiniteScroll
for handling infinite scrolling behavior:
jsximport React, { useState, useEffect } from 'react';
const InfiniteScroll = () => {
const [page, setPage] = useState(1);
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
useEffect(() => {
setLoading(true);
fetchData(page)
.then(newData => {
setData(prevData => [...prevData, ...newData]);
setHasMore(newData.length > 0);
setLoading(false);
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, [page]);
const handleScroll = () => {
if (!loading && hasMore && window.innerHeight + window.scrollY >= document.body.scrollHeight) {
setPage(prevPage => prevPage + 1);
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return (
<div>
{data.map(item => (
<div key={item.id}>
{/* Render your data */}
</div>
))}
{loading && <div>Loading...</div>}
</div>
);
};
export default InfiniteScroll;
Use the Infinite Scroll Component:
Use the InfiniteScroll
component in your app wherever you want to display paginated infinite scroll data.
jsximport React from 'react';
import InfiniteScroll from './InfiniteScroll';
const App = () => {
return (
<div>
<h1>Paginated Infinite Scroll</h1>
<InfiniteScroll />
</div>
);
};
export default App;
Style Your Component (Optional):
Style your InfiniteScroll
component as needed to fit your application's design.
With these steps, you've created a paginated infinite scroll in your React.js app. As the user scrolls down the page, more data is dynamically loaded, providing a seamless browsing experience.