I have implemented a pagination component in React, but encountered an issue where all pages were being displayed, causing the page to expand and require horizontal scrolling. Is there a way to limit the display to only 20 pages while still allowing for more to be added dynamically without taking up excessive space?
I attempted some logic using:
if (numberOfPages > 20 ) { return }
The variable numberOfPages represents the total number of pages.
I am unsure of the best approach to achieve this task.
Below is the code snippet I am currently working with:
const Pagination = ({ numberOfPages, page, setPage }: any) => {
const pageNumbers = (numberOfPages: number) => {
let pages = [];
for (let i = 1; i <= numberOfPages; i++) {
pages.push(
<span
key={i}
onClick={e => setPage(i)}
className={page === i ? "active" : ""}
>
{i}
</span>
);
// if (numberOfPages > 20 ) {
// return
// }
}
return pages;
};
return (
<div className="pagination">
<div className="page-numbers">
<span
onClick={e => (page === 1 ? {} : setPage(page - 1))}
className={page === 1 ? "disabled" : ""}
>
«
</span>
{pageNumbers(numberOfPages)}
<span
onClick={e => (page === numberOfPages ? {} : setPage(page + 1))}
className={page === numberOfPages ? "disabled" : ""}
>
»
</span>
</div>
</div>
);
};
export default Pagination;