I’m working on a React application where I need to implement a custom pagination component. The pagination should display up to 5 page links at a time, always include the first and last page links, and handle cases where there are fewer than 5 pages or when the current page is near the start or end of the pagination.
import React, { useState } from 'react';
const Pagination = ({ total, current, onPageChange }) => {
const [currentPage, setCurrentPage] = useState(current);
const handlePageChange = (page) => {
setCurrentPage(page);
onPageChange(page);
};
const renderPageNumbers = () => {
// Need help with the logic here
};
return (
<div className="pagination">
<button
onClick={() => handlePageChange(1)}
disabled={currentPage === 1}
>
First
</button>
{renderPageNumbers()}
<button
onClick={() => handlePageChange(total)}
disabled={currentPage === total}
>
Last
</button>
</div>
);
};
export default Pagination;
I expect the renderPageNumbers
function to generate up to 5 page links dynamically based on the current page and total pages, ensuring the first and last page links are always visible. For example, if I have 10 pages and I’m on page 6, it should display links like 1 ... 4 5 6 7 8 ... 10
.
Currently, I’m unsure how to dynamically generate and display these page links in the renderPageNumbers
function. The pagination doesn’t adjust properly when the current page changes, and I’m struggling with the logic to handle different edge cases effectively.
So my question is how can I implement the renderPageNumbers
function to achieve the described pagination behavior in React? Any advice or code examples would be greatly appreciated!
Iljubaev Marat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.