Pagination is an important way to show a lot of content in a small space on our website. In this article, we will create a simple pagination in ReactJS with Material UI. However, we can develop it without a library, but having one can make the process easier.
So let's get started.
Table of contents:
- Introduction to Pagination in ReactJS
- Creating a Project
- Exploring Different Styles of Pagination with Material UI
- React MUI Pagination Props List
- React MUI Pagination CSS Rules
- Optimizing Performance
Introduction to Pagination in ReactJS
Well, pagination is used for browsing a dataset where the data will be broken down into smaller portions, which makes your work easy to handle. Pagination reduces long load times, is more user-friendly, and makes it easier to follow the data.
Let's create a project so we can see how to implement pagination in a React project using Material UI.
Creating a Project
Before we start, ensure you have Node.js and npm installed on your machine. Create a new React project using the Create React App:
npx create-react-app pagination-demo
cd pagination-demo
Installing the Material UI Library
Install Material UI in your project using the following command:
npm install @mui/material @emotion/react @emotion/styled
Okay, we've completed the installation correctly so far. Now, to display data in the browser, you have two options. You can either build your own API to fetch the data dynamically or you can create a posts.json file within your project. This JSON file will serve as storage for your data, which you can subsequently import into your project for utilization.
Let's proceed by creating a posts.json file in your src directory and adding your data there.
[
{
"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, 2023",
"description": "Discover the fundamentals of Python programming for data science. This article covers essential libraries, data manipulation, and visualization techniques."
},
{
"title": "Deep Learning: A Step-by-Step Approach",
"date": "Jul 22, 2023",
"description": "A beginner's guide to deep learning, explaining the key concepts, architectures, and how to implement your own deep learning models using popular frameworks."
},
{
"title": "Computer Vision: Algorithms and Applications",
"date": "Jul 23, 2023",
"description": "An introduction to computer vision, covering essential algorithms for object detection, image segmentation, and the wide range of applications in various industries."
},
{
"title": "Introduction to Machine Learning: Concepts and Techniques",
"date": "Jul 25, 2023",
"description": "Get started with machine learning by understanding the core concepts, different types of learning algorithms, and practical implementation tips."
}
]
Now, create a file named PaginationComponent.jsx in your project's src directory. This file will handle the logic for pagination. Next, import the necessary Material UI components into this file. We'll use the Pagination component from Material UI for managing pagination.
import Pagination from '@mui/material/Pagination';
// OR
import { Pagination } from '@mui/material';
Here is the entire code for pagination:
// src/PaginationComponent.js
import React, { useState, useEffect } from 'react';
import { Pagination } from '@mui/material';
import postsData from './posts.json';
const itemsPerPage = 3;
function PaginationComponent() {
const [page, setPage] = useState(1);
const [posts, setPosts] = useState([]);
useEffect(() => {
// Simulate fetching posts from JSON
setPosts(postsData);
}, []);
const handleChange = (event, value) => {
setPage(value);
};
const paginatedPosts = posts.slice((page - 1) * itemsPerPage, page * itemsPerPage);
return (
<div>
<div className="posts">
{paginatedPosts.map(post => (
<Post key={post.id} post={post} />
))}
</div>
<Pagination
count={Math.ceil(posts.length / itemsPerPage)}
page={page}
onChange={handleChange}
color="primary"
className="pagination"
/>
</div>
);
}
function Post({ post }) {
return (
<div className="post">
<h2>{post.title}</h2>
<p className='date'>{post.date}</p>
<p>{post.description}</p>
</div>
);
}
export default PaginationComponent;
This component utilizes React hooks (useState, useEffect) and Material UI's Pagination component to manage and display paginated posts fetched from a JSON file. Initially, it imports the necessary modules and sets up state variables for managing the current page (page) and the array of posts (posts). When the component mounts, the useEffect hook fetches data from posts.json, updating the posts state with the retrieved data. The handleChange function is triggered when users interact with the Pagination component, updating the page state to reflect the current page being viewed.
Each page displays a subset of posts based on the current page state, ensuring smooth navigation through the list of posts. The count prop in the Pagination component dynamically calculates the total number of pages using Math.ceil method, adjusting automatically as new posts are added. Additionally, the onChange prop links to handleChange to update the displayed page when users navigate through pages.
The color prop sets the pagination component's style to a primary color theme, while the className prop applies custom styling defined elsewhere in the project for a consistent appearance across the application. This setup ensures a user-friendly experience for browsing through a potentially large collection of posts.
Next, import this PaginationComponent component in the main App.js file.
// src/App.js
import React from 'react';
import PaginationComponent from './PaginationComponent';
import './App.css';
function App() {
return (
<div className="App">
<h1>Blog</h1>
<PaginationComponent />
</div>
);
}
export default App;
In this code, we import the PaginationComponent for displaying pagination functionality and include App.css for styling. We render the PaginationComponent within the return statement of the App component.
For styling, you can include this code in your App.css file.
/* src/App.css */
* {
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
.App h1 {
text-align: center;
}
.posts {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
}
.post {
border: 1px solid #efefef;
border-radius: 8px;
padding: 15px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
width: 280px;
height: 200px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.post h2 {
font-size: 18px;
overflow: hidden;
}
.post p {
margin: 0;
flex-grow: 1;
overflow: hidden;
font-size: 14px;
}
.post .date {
font-size: 12px;
}
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
Ok great! We've completed it, and your project UI should resemble this.
Now let's look at how we can customize the styling of the pagination for our project.
Exploring Different Styles of Pagination with Material UI
Outlined pagination
We can give the pagination buttons rounded borders by setting the variant prop to 'outlined'.
<Pagination variant="outlined" />
Rounded pagination
We can modify the shape of the pagination button by using the shape prop.
<Pagination shape="rounded" />
Material UI provides this kind of many props that help us customize our project to suit its specific needs. Here is the list of props.
React MUI Pagination Props List
boundaryCount(number):
Using the boundaryCount prop, we specify how many page numbers to show at the beginning and end of the pagination. The default value is 1.
<Pagination boundaryCount={2} />
classes(object):
Using the classes prop, we can customize or extend the styles of the components.
<Pagination classes={{ root: 'custom-class', ul: 'custom-ul-class' }} />
sx (Array<func / object/bool> / func / object):
Using the sx prop, we can define inline styles or system overrides directly on Material-UI components, enabling precise customization of their appearance and behavior without extensive external CSS dependencies.
<Pagination sx={{ m: 1, p: 1, border: "5px solid red" }} />
color(primary/secondary/standard):
Using the color prop, we can specify the color variant of the pagination component. By default, it is set to 'standard'.
<Pagination color="primary" />
count(integer):
Using the count prop, we can specify the total number of pages.
<Pagination count={10} />
siblingCount(integer):
Using the siblingCount prop, we can specify the number of sibling pages to display. By default, it is set to 1.
<Pagination siblingCount={2} />
page(integer):
Using the page prop, we can specify the current page number. By default, it is set to 1.
<Pagination page={2} />
disabled(bool):
Using the disabled prop, we can disable the pagination component by setting it to true. By default, it is set to false.
<Pagination disabled />
hideNextButton(bool):
Using the hideNextButton prop, we can hide the "Next" button. The default value is false.
<Pagination hideNextButton />
hidePrevButton(bool):
Using the hidePrevButton prop, we can hide the "Prev" button. The default value is false.
<Pagination hidePrevButton />
showFirstButton(bool):
Using the showFirstButton prop, we can determine whether to display the "first" button. The default value is false.
<Pagination showFirstButton />
showLastButton(bool):
Using the showLastButton prop, we can determine whether to display the "last" button. The default value is false.
<Pagination count={10} showLastButton />
getItemAriaLabel(func):
Using the getItemAriaLabel prop, we can provide a function to customize the aria-label for each page item, allowing accessibility enhancements tailored to specific pagination needs.
<Pagination getItemAriaLabel={(type, page, selected) => `Page ${page}`} />
The getItemAriaLabel is a function that generates an aria-label for each page item. It takes parameters (type, page, selected), where type indicates the type of the pagination item (e.g., "page", "next", "previous"), a page is the page number, and selected indicates if the current item is selected.
renderItem(func):
The renderItem prop is a function that you can provide to the pagination component. It allows you to define how each page item should be rendered. Each page item represents a single page number or a navigation control (like "previous", "next", "first", or "last").
<Pagination
renderItem={(item) => (
<PaginationItem
{...item}
component="a"
href={`#page=${item.page}`}
/>
)}
/>
shape(circular/rounded):
Using the shape prop, we can specify the shape of the pagination items. By default, it is set to 'circular'.
<Pagination shape="rounded" />
size(small/medium/large):
Using the size prop, we can specify the size of the pagination component. The default size is 'medium'.
<Pagination count={10} size="small" />
variant(outlined/text):
Using the variant prop, we can specify the variant of the pagination component. The default variant is 'text'.
<Pagination count={10} variant="outlined" />
React MUI Pagination CSS Rules
Material-UI (MUI) provides several CSS classes that allow you to customize the appearance of the pagination component. Here are some of the key CSS rules and classes you can use:
1. root (.MuiPagination-root)
We can use this prebuilt class name to apply styles to the main element of the Pagination component.
.MuiPagination-root {
padding: 10px;
background-color: #f0f0f0;
}
2. ul (.MuiPagination-ul)
We can use this prebuilt class name to apply styles to the ul element within the Pagination component.
.MuiPagination-ul {
list-style: none;
display: flex;
justify-content: center;
padding: 0;
}
3. outlined (.MuiPagination-outlined)
We can use this prebuilt class name to apply styles to the main element when the variant prop is set to 'outlined'.
.MuiPagination-outlined {
border: 1px solid #ccc;
border-radius: 4px;
}
4. text (.MuiPagination-text)
We can use this prebuilt class name to apply styles to the root element when the variant prop is set to 'text'.
.MuiPagination-text {
color: #1976d2;
}
You can customize the style using the pre-existing class name like this. Additionally, you can create your own custom styles using the className prop.
Optimizing Performance
- Use Memoization: Memoize components and data fetching functions to avoid unnecessary re-renders.
- Lazy Loading: Load data only when needed, improving initial page load times.
- Virtualization: Implement virtual lists for rendering large datasets efficiently.
Conclusion
That was the basics of pagination in ReactJS, from a beast-level comprehension to an actual project structure setup. I just took you through a few types of pagination with the Material UI, a brief about React MUI pagination props, and a little CSS to not get hung. Further, we touched base on some optimization techniques to improve performance. With those insights, developers are better equipped to integrate more efficient and customizable pagination components in React applications for an intuitive user experience on their UIs.
If you have any questions about this article or related to web development, you can ask them in the question box given below, you will get the answers soon.