Build A Custom Pagination Component In ReactJS From Scratch!
In this article, we'll walk through the process of building a custom pagination component in ReactJS from scratch. Pagination is a common feature in web applications that allows users to navigate through multiple pages of content, such as articles, search results, or product listings.
Prerequisites
Before we begin, make sure you have Node.js and npm (Node Package Manager) installed on your system. You'll also need a basic understanding of ReactJS and JavaScript.
Setting up the Project
npx create-react-app
npx create-react-app
pagination-demo
pagination-demo
cd pagination-demo
cd pagination-demo
npm install react-bootstrap
npm install react-bootstrap
Creating the Pagination Component
// src/Pagination.js import React from 'react'; import { Pagination } from 'react-bootstrap'; const CustomPagination = ({ currentPage, totalPages, onPageChange }) => { const handleClick = (pageNumber) => { onPageChange(pageNumber); }; return ( <Pagination> <Pagination.First onClick={() => handleClick(1)} /> <Pagination.Prev onClick={() => handleClick(currentPage > 1 ? currentPage - 1 : 1)} /> {Array.from({ length: totalPages }, (_, index) => index + 1).map( (pageNumber) => ( <Pagination.Item key={pageNumber} active={pageNumber === currentPage} onClick={() => handleClick(pageNumber)} > {pageNumber} </Pagination.Item> ) )} <Pagination.Next onClick={() => handleClick(currentPage < totalPages ? currentPage + 1 : totalPages) } /> <Pagination.Last onClick={() => handleClick(totalPages)} /> </Pagination> ); }; export default CustomPagination;
In this component:
- We import the Pagination component from react-bootstrap.
- The CustomPagination component takes three props: currentPage, totalPages, and onPageChange.
- Inside the component, we define a handleClick function to handle pagination button clicks.
- We render pagination buttons using the Pagination.Item component and handle their clicks accordingly.