Hello developers! Welcome to this article. Users can efficiently navigate a website through pagination by compacting large data sets.
With the help of examples, we will learn how to implement pagination in the ReactJS application. In the last, we will also learn how to implement pagination in an alternative way so that you can become an expert. Read this article carefully, and by the end, you’ll fully understand how pagination works.
So let's get started.
Table of contents:
- What is Pagination?
- Why Use Pagination in Web Applications?
- Building logic for this project
- Getting start project
- Exploring Alternative Pagination Approaches
What is Pagination?
The concept of pagination consists of breaking up a lot of content into smaller, more manageable pieces. Think of it like a book with chapters; it makes everything easier to navigate.
Why Use Pagination in Web Applications?
Better user experience: Users can easily navigate the content with smaller sections of the website, reducing the hassle of scrolling through large amounts of data.
Faster page loading: Loading content in smaller chunks makes new content load immediately, which is especially beneficial for websites with a lot of data or a slow Internet connection.
Enhanced access: We can give users access to numbered pages or navigation buttons (previous, next) to load new content, making it easier for users to find specific information.
Better organization: Pagination organizes our content logically into pages, similar to chapters in a book, making it easier for users to find and interact with the information they want.
SEO benefits: When search engines can easily scan and list paginated content, it boosts the chances of individual pages appearing in search results, potentially attracting more visitors to a website.
Building logic for this project
I have built the logic of this project based on the one I created in this article, so make sure to follow along.
To implement pagination in ReactJS for this project, start by managing the currentPage state and defining postsPerPage to control how many posts are displayed per page. Calculate which posts to show using indexOfLastPost and indexOfFirstPost based on the current page and postsPerPage. Implement functions like paginate, handlePrevClick, and handleNextClick to manage page changes. Render the blog posts dynamically based on the current page state.
In the Pagination component, calculate total pages (totalPages) and generate page numbers dynamically to allow users to navigate between pages smoothly. Integrate these components to create a seamless user experience for browsing through blog content.
If you understand how to apply this logic, that's great! If not, don't worry. We'll create a project directly to help you grasp everything. Building logic is essential before starting any project because it lays the foundation for a successful outcome.
Getting start project
We will create a way to show many blog posts in small parts. We will only show 3 posts at a time. To see more posts, we will add buttons below the posts so users can click and view all the posts easily.
Setting Up the Project
To start this project, we first need data to show the blog information. We will use a JSON file to store our blog posts. Create a file named posts.json in your project directory and add some sample blog data to it. You can also create your own API to get data, but for this project, we will use the data from the posts.json file.
Create a file named posts.json in the src directory and include the following code:
[
{
"title": "Top 5 CSS Frameworks to Use in 2023",
"date": "Jan 15, 2023",
"description": "A detailed comparison of the top 5 CSS frameworks in 2023, helping you choose the best one for your web development needs."
},
{
"title": "Building Scalable APIs with Node.js",
"date": "Feb 22, 2023",
"description": "Guide on creating scalable and efficient APIs using Node.js, covering best practices and performance tips."
},
{
"title": "Exploring the Capabilities of Rust Programming Language",
"date": "Mar 5, 2023",
"description": "An overview of Rust programming language, its unique features, and why it's gaining popularity among developers."
},
{
"title": "Understanding Progressive Web Apps",
"date": "Apr 12, 2023",
"description": "Explore what Progressive Web Apps (PWAs) are, their benefits, and how they can improve user experience on mobile and desktop."
},
{
"title": "How to Implement Microservices Architecture",
"date": "Jul 21, 2023",
"description": "A comprehensive guide on microservices architecture, including its advantages and steps to implement it in your projects."
},
{
"title": "Creating Responsive Designs with Flexbox",
"date": "Dec 5, 2023",
"description": "Learn how to use CSS Flexbox to create responsive web designs that look great on any device, with practical examples and tips."
},
{
"title": "Introduction to Blockchain Technology",
"date": "Dec 1, 2023",
"description": "Understand the fundamentals of blockchain technology, its use cases, and its potential impact on various sectors."
},
{
"title": "Developing Mobile Apps with Flutter",
"date": "Nov 18, 2023",
"description": "An introductory guide to Flutter, Google's UI toolkit, and how to use it for building natively compiled applications for mobile, web, and desktop."
},
{
"title": "Leveraging Artificial Intelligence in Business",
"date": "Oct 20, 2023",
"description": "Explore how artificial intelligence can be used to drive business growth, improve efficiency, and gain a competitive edge."
},
{
"title": "The Evolution of Cloud Computing",
"date": "Jan 15, 2024",
"description": "A historical perspective on the evolution of cloud computing, from its inception to its current state and future trends."
},
{
"title": "Getting Started with DevOps",
"date": "Jan 10, 2024",
"description": "A beginner's guide to DevOps, covering its principles, practices, and the tools you need to implement a successful DevOps strategy."
},
{
"title": "Mastering Data Visualization with D3.js",
"date": "Feb 10, 2024",
"description": "Learn how to create stunning data visualizations using D3.js, a powerful JavaScript library for producing dynamic, interactive data visualizations in web browsers."
},
{
"title": "Understanding Serverless Architecture",
"date": "Feb 25, 2024",
"description": "An introduction to serverless architecture, its advantages, and how it can simplify the deployment and scaling of applications."
},
{
"title": "Building Interactive Websites with JavaScript",
"date": "Mar 15, 2024",
"description": "A guide on how to create interactive and dynamic websites using JavaScript, including examples and best practices."
},
{
"title": "The Rise of Edge Computing",
"date": "Apr 20, 2024",
"description": "An exploration of edge computing, its benefits, and how it is transforming the way data is processed and analyzed at the edge of the network."
},
{
"title": "Intro to Kubernetes for Beginners",
"date": "May 10, 2024",
"description": "Learn the basics of Kubernetes, an open-source system for automating deployment, scaling, and management of containerized applications."
},
{
"title": "Enhancing User Experience with Design Thinking",
"date": "May 12, 2024",
"description": "Learn how design thinking can be applied to enhance user experience, with a focus on empathy, prototyping, and iterative design."
},
{
"title": "The Future of Quantum Computing",
"date": "Jun 14, 2024",
"description": "An in-depth look at the potential of quantum computing and how it could revolutionize various industries in the future."
},
{
"title": "Introduction to Natural Language Processing",
"date": "Jun 18, 2024",
"description": "Discover the basics of natural language processing (NLP), its applications, and how it enables computers to understand and process human language."
},
{
"title": "Best Practices for Secure Web Development",
"date": "Jun 20, 2024",
"description": "An article outlining the best practices for ensuring security in web development, including tips on protecting against common vulnerabilities."
},
{
"title": "Getting Started with Python for Data Science",
"date": "Jul 20, 2024",
"description": "Discover the fundamentals of Python programming for data science. This article covers essential libraries, data manipulation, and visualization techniques."
}
]
Creating the Blog Component
Next, create a Blog.jsx file where we'll display our blog posts and handle pagination. This component will use the state to manage the current page and calculate which posts to display.
// src\Blog.js
import React, { useState } from 'react';
import Pagination from './Pagination';
import posts from './posts.json'; // Import the JSON data
const Blog = () => {
const [currentPage, setCurrentPage] = useState(1);
const postsPerPage = 3;
// Calculate the current posts to display
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = (pageNumber) => setCurrentPage(pageNumber);
// Handle Prev button click
const handlePrevClick = () => {
if (currentPage > 1) {
setCurrentPage(currentPage - 1);
}
};
// Handle Next button click
const handleNextClick = () => {
if (currentPage < Math.ceil(posts.length / postsPerPage)) {
setCurrentPage(currentPage + 1);
}
};
return (
<div>
<h1>Blog</h1>
<div className="blog-container">
{currentPosts.map((post, index) => (
<div key={index} className="blog-box">
<h2 className="blog-title">{post.title}</h2>
<p className="blog-date">{post.date}</p>
<p className="blog-description">{post.description}</p>
</div>
))}
</div>
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
currentPage={currentPage}
handlePrevClick={handlePrevClick}
handleNextClick={handleNextClick}
/>
</div>
);
};
export default Blog;
In this component, we use useState hook to manage the current page. We calculate which posts to display using indexOfFirstPost and indexOfLastPost. We create functions like paginate, handlePrevClick, and handleNextClick to handle page changes. Finally, we render the blog posts based on the current page and display the Pagination component.
Creating the Pagination Component
Create a Pagination.jsx file to handle the pagination logic. This component will generate the page numbers and handle navigation between pages.
// src\Pagination.js
import React from 'react';
const Pagination = ({ postsPerPage, totalPosts, paginate, currentPage, handlePrevClick, handleNextClick }) => {
const totalPages = Math.ceil(totalPosts / postsPerPage);
const maxPagesToShow = 5;
// Function to generate page numbers
const getPageNumbers = () => {
const pageNumbers = [];
const halfMaxPagesToShow = Math.floor(maxPagesToShow / 2);
// Calculate start and end page numbers based on current page
let startPage = Math.max(2, currentPage - halfMaxPagesToShow);
let endPage = Math.min(totalPages - 1, currentPage + halfMaxPagesToShow);
// Adjust startPage and endPage if current page is near the edges
if (currentPage <= halfMaxPagesToShow) {
endPage = maxPagesToShow;
} else if (currentPage > totalPages - halfMaxPagesToShow) {
startPage = totalPages - maxPagesToShow + 1;
}
startPage = Math.max(2, startPage);
endPage = Math.min(totalPages - 1, endPage);
// Always show the first page
pageNumbers.push(
<li key={1} className={`page-item ${currentPage === 1 ? 'active' : ''}`}>
<button onClick={() => paginate(1)} className="page-link">
1
</button>
</li>
);
// Add ellipsis before the startPage if needed
if (startPage > 2) {
pageNumbers.push(
<li key="ellipsis-start" className="page-item disabled">
<span className="page-link">...</span>
</li>
);
}
// Generate page numbers between startPage and endPage
for (let i = startPage; i <= endPage; i++) {
pageNumbers.push(
<li key={i} className={`page-item ${i === currentPage ? 'active' : ''}`}>
<button onClick={() => paginate(i)} className="page-link">
{i}
</button>
</li>
);
}
// Add ellipsis after the endPage if needed
if (endPage < totalPages - 1) {
pageNumbers.push(
<li key="ellipsis-end" className="page-item disabled">
<span className="page-link">...</span>
</li>
);
}
// Always show the last page
if (totalPages > 1) {
pageNumbers.push(
<li key={totalPages} className={`page-item ${currentPage === totalPages ? 'active' : ''}`}>
<button onClick={() => paginate(totalPages)} className="page-link">
{totalPages}
</button>
</li>
);
}
return pageNumbers;
};
return (
<nav>
<ul className="pagination">
<li className={`page-item ${currentPage === 1 ? 'disabled' : ''}`}>
<button onClick={handlePrevClick} className="page-link">
Prev
</button>
</li>
{getPageNumbers()}
<li className={`page-item ${currentPage === totalPages ? 'disabled' : ''}`}>
<button onClick={handleNextClick} className="page-link">
Next
</button>
</li>
</ul>
</nav>
);
};
export default Pagination;
In this component, we calculate the total number of pages and dynamically generate the page numbers, making sure the first and last pages are always shown. We add ellipses (…) if there are gaps between the start/end pages and the first/last pages. We also handle the Prev and Next buttons to navigate through the pages.
Styling the Components
Create an App.css file to style the blog and pagination components. This is just for this project. If you have already created your project, you can create your own style and just use the logical code from above. If you are practicing, you can use this CSS code in your project.
/* src\App.css */
/* General reset and font styles */
body {
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
h1 {
text-align: center;
}
/* Container for the blog grid */
.blog-container {
display: flex;
justify-content: center;
gap: 20px;
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
/* Individual blog box */
.blog-box {
border: 1px solid #ddd;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
width: calc(33.333% - 20px);
margin: 10px 0;
}
.blog-title, .blog-date, .blog-description {
margin: 15px;
}
.blog-title {
font-size: 1.25em;
}
.blog-date {
font-size: 0.9em;
}
/* Pagination styles */
.pagination {
display: flex;
justify-content: center;
list-style-type: none;
margin-top: 20px;
}
.page-item {
margin: 0 5px;
}
.page-link {
border: 1px solid #6a6a6a;
padding: 10px 15px;
color: #000;
background-color: #ededed;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s, color 0.3s;
display: flex;
}
.page-link:hover {
background-color: #000;
color: white;
}
.page-item.active .page-link {
background-color: #000;
color: white;
}
.page-item.disabled .page-link {
color: #c1c1c1;
cursor: not-allowed;
border-color: #ccc;
}
.page-item.disabled .page-link:hover {
background-color: transparent;
}
Integrating Everything in App.js
Finally, add the Blog component to the main App.js file.
// src\App.js
import React from 'react';
import Blog from './Blog';
import './App.css';
const App = () => {
return (
<div className="App">
<Blog />
</div>
);
};
export default App;
Congratulations, you've completed it! Your project's UI should now resemble this.
Exploring Alternative Pagination Approaches
React is popular today because it is easy to learn and use. Developers can easily create projects with its many component libraries.
React has a popular library called Material UI which makes it easy to create pagination. Check out this article to learn how to create pagination with Material UI. However, many developers also use react-paginate, react-bootstrap-pagination, and react-js-pagination libraries to handle pagination in their projects. It completely depends on your project needs and your preferences. You can choose any library based on what you know and what your project requires.
You might be wondering why we didn't use this library in this project when we can easily create pagination with the help of the external library. The reason is that, as a professional developer, you should learn multiple ways to achieve the same goal.
Conclusion
This way, you can implement a fully functional pagination system in your ReactJS application, with the number of buttons in the Pagination component increasing as the number of your blog posts grows. For example, in this project, the Blog component manages the display of blog posts, while the Pagination component handles the navigation logic. The App.css file ensures that everything looks polished and user-friendly. You can organize and present large amounts of data clearly and easily with this setup.
If you have any questions about this article or related to web development, you can ask them in the question box given below, and you will get the answer soon.