Pagination
Example: Below is an example of Pagination with React Hooks:
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.pagination {
display: flex;
justify-content: center;
}
h3 {
margin: 10px;
}
h1 {
background-color: green;
color: aliceblue;
padding: 10px 20px;
}
import React, {
useState,
useEffect
} from 'react';
import './App.css';
const Pagination = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
fetchPosts();
}, [currentPage]);
const fetchPosts = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${currentPage}&_limit=10`);
const data = await response.json();
setPosts(data);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
const handlePageChange = (newPage) => {
setCurrentPage(newPage);
};
return (
<div>
<h1>Pagination</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post">
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
{loading && <div>Loading...</div>}
</div>
<div className="pagination" >
<button onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}>
Previous
</button>
<h3>
{currentPage}
</h3>
<button onClick={() => handlePageChange(currentPage + 1)}>
Next
</button>
</div>
</div>
);
};
export default Pagination;
Start your application using the following command.
npm start
Output:
Pagination and Infinite Scrolling with React Hooks
In the world of web development, making long lists of items like posts, products, or comments easy to navigate is super important. Two common ways to do this are Pagination and Infinite Scrolling. In this guide, we’ll walk through how to implement both of these techniques using React Hooks. Don’t worry if you’re new to React or programming – we’ll take it step by step!
Contact Us