Infinite scrolling is a popular technique used in web development to provide a seamless and user-friendly experience when dealing with large amounts of data. This technique allows content to be loaded dynamically as the user scrolls down the page, rather than having to load all the content at once.
In this tutorial, we will guide you through implementing infinite scrolling in a ReactJS application. We will use a simple example of fetching data from an API and displaying it in a list that will grow as the user scrolls down the page.
Step 1: Setting up your React application
First, make sure you have Node.js installed on your machine. You can check this by running the following command in your terminal:
node -v
If Node.js is not installed, you can download it from the official website (https://nodejs.org/).
Next, create a new React application using Create React App by running the following command in your terminal:
npx create-react-app infinite-scrolling
This will create a new React application called infinite-scrolling
. Navigate to the project directory by running:
cd infinite-scrolling
Step 2: Fetching data from an API
For this tutorial, we will use the JSONPlaceholder API, which provides fake JSON data for testing and prototyping. You can access the API endpoint for fetching posts at:
https://jsonplaceholder.typicode.com/posts
In your src
directory, create a new file called api.js
and add the following code to fetch the posts data:
export const fetchPosts = async (page) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
const data = await response.json();
return data;
};
Step 3: Creating a component for the infinite scrolling list
Create a new file called InfiniteScrollList.js
in your src
directory. We will create a functional component that will render a list of posts and implement the infinite scrolling functionality.
import React, { useEffect, useState } from 'react';
import { fetchPosts } from './api';
const InfiniteScrollList = () => {
const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
useEffect(() => {
const fetchData = async () => {
const data = await fetchPosts(page);
setPosts((prevPosts) => [...prevPosts, ...data]);
};
fetchData();
}, [page]);
const handleScroll = () => {
if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight) return;
setPage((prevPage) => prevPage + 1);
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return (
<div>
{posts.map((post) => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default InfiniteScrollList;
Step 4: Rendering the InfiniteScrollList component
In the App.js
file in your src
directory, import the InfiniteScrollList
component and render it in the App
component.
import React from 'react';
import './App.css';
import InfiniteScrollList from './InfiniteScrollList';
function App() {
return (
<div className='App'>
<h1>Infinite Scrolling in React</h1>
<InfiniteScrollList />
</div>
);
}
export default App;
Step 5: Styling your components
You can style your components using CSS in the App.css
file in your src
directory.
.App {
text-align: center;
}
h1 {
color: #333;
}
div {
margin: 10px;
padding: 10px;
border: 1px solid #eaeaea;
}
Step 6: Running your React application
You can now run your React application by running the following command in your terminal:
npm start
This will start the development server and open your application in a new browser tab. You should see a list of posts being rendered and as you scroll down the page, more posts will be fetched and added to the list.
Congratulations! You have successfully implemented infinite scrolling in a ReactJS application. This technique can be applied to various use cases where you want to load data dynamically as the user interacts with the page. Feel free to customize the implementation further based on your requirements and experiment with different data sources and UI components. Happy coding! 🔥🚀
Remember to clean up event listeners and handle potential memory leaks in your component by using the useEffect hook and cleanup function. This will ensure that your application remains performant and responsive even when dealing with large datasets.
perfect name for your channel.. ha ha…
So is it like lazy loading??
You are awesome 👍
Great