What Is Paginate In React

What Is Paginate?

If you are building a React project and you have a large amount of list data, React pagination functionality helps you to manage data on a single page.

With pagination, users can click on “Next”, “Previous”, or page numbers to move between pages dynamically. This improves both the speed of the app and the user experience, because it’s easier to browse data in smaller parts.

React provides a pre-built React Paginate library to add pagination to the project.

Why Use Pagination in React?

  1. Improved Performance: A large data set can slow down our app in a single time frame. Pagination loads that data into smaller parts and reducing the load time.
  2. Better Data Management: Pagination allows users to easily manage and organise content, especially in heavy-data applications.

How To Import Paginate In React?

we can use two methods for pagination, custom paginate and using the pre-built React-Paginate library.

The React-Paginate library is an excellent choice for more advanced features. It provides customizable pagination controls, supports various configurations and handles navigation in our projects.

Open your terminal and run this command:

npm install react-paginate

or if you’re using Yarn, run this command:

yarn add react-paginate

Import it into your React component

import ReactPaginate from 'react-paginate';
import './App.css'; // Optional: add custom styles or use default styles

Note: You can also import default CSS from the library if you don’t want to write your own CSS:

import 'react-paginate/dist/react-paginate.css';

Use This Code Into JSX

<ReactPaginate
pageCount={totalPages}
onPageChange={handlePageClick}
previousLabel={'← Previous'}
nextLabel={'Next →'}
containerClassName={'pagination'}
activeClassName={'active'}
/>

Real Example of React Paginate

import React, { useState } from 'react';
import ReactPaginate from 'react-paginate';

function PaginatedComponent({ data }) {
const [currentPage, setCurrentPage] = useState(0);
const itemsPerPage = 5;

// Calculate the data for the current page
const offset = currentPage * itemsPerPage;
const currentItems = data.slice(offset, offset + itemsPerPage);
const pageCount = Math.ceil(data.length / itemsPerPage);

const handlePageClick = ({ selected }) => {
setCurrentPage(selected);
};

return (
<div>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>

<ReactPaginate
previousLabel={'Previous'}
nextLabel={'Next'}
breakLabel={'...'}
pageCount={pageCount}
marginPagesDisplayed={2}
pageRangeDisplayed={3}
onPageChange={handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
</div>
);
}

export default PaginatedComponent;

Code explanations:

  • ReactPaginate Component: The library component handles pagination UI with various props:
    • previousLabel and nextLabel: Set labels for navigation buttons.
    • pageCount: Determines the total number of pages.
    • onPageChange: Updates the currentPage when a page is selected.
    • containerClassName and activeClassName: Add CSS classes to customize pagination styling.

Styling with React-Paginate

You can style the pagination component by adding CSS classes:

.pagination {
display: flex;
list-style: none;
padding: 0;
}

.pagination li {
margin: 0 5px;
}

.pagination li a {
text-decoration: none;
padding: 8px 12px;
color: black;
border: 1px solid #ddd;
}

.pagination li a.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}

Example of Custom Pagination

import React, { useState } from 'react';

function CustomPaginator({ items }) {
const [pageNum, setPageNum] = useState(1);
const recordsPerPage = 5;

// Total number of pages
const pageTotal = Math.ceil(items.length / recordsPerPage);

// Slice out visible records for current page
const firstRecordIndex = (pageNum - 1) * recordsPerPage;
const visibleRecords = items.slice(firstRecordIndex, firstRecordIndex + recordsPerPage);

// Go to next page
const goToNext = () => {
if (pageNum < pageTotal) {
setPageNum((prev) => prev + 1);
}
};

// Go to previous page
const goToPrevious = () => {
if (pageNum > 1) {
setPageNum((prev) => prev - 1);
}
};

// Go to specific page
const changePage = (num) => {
setPageNum(num);
};

return (
<div>
<ul>
{visibleRecords.map((entry, idx) => (
<li key={idx}>{entry}</li>
))}
</ul>

<div>
<button onClick={goToPrevious} disabled={pageNum === 1}>
Previous
</button>

{Array.from({ length: pageTotal }, (_, idx) => (
<button
key={idx}
onClick={() => changePage(idx + 1)}
className={pageNum === idx + 1 ? 'active' : ''}
>
{idx + 1}
</button>
))}

<button onClick={goToNext} disabled={pageNum === pageTotal}>
Next
</button>
</div>
</div>
);
}

export default CustomPaginator;

Code explanations:

  • currentItems: Filters the data array to display only the items for the current page.
  • totalPages: Calculates the number of pages by dividing the total items by itemsPerPage.
  • Navigation Functions: handleNextPage and handlePrevPage increment or decrement the currentPage value while preventing it from exceeding boundaries.
  • Page Buttons: A loop generates page numbers for navigation, and sets the current page upon button click.
button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}

button.active {
background-color: #007bff;
color: white;

Leave a Comment

BoxofLearn