I have a PaginationComponent that currently works well, looping through a function to generate pagination ranges and displaying ellipses using -1 and -2 to indicate gaps. I want to refactor this component to use useState and useEffect for managing pagination state and dynamically displaying ellipses. Additionally, I want to understand any performance implications given that the component is used with large data tables, sometimes with multiple instances on the same page.
Here’s the original code:
const PaginationComponent: FC<PaginationProps> = ({
currentPage,
handlePageChange,
handlePageSizeChange,
pageSize,
total,
title,
}) => {
const totalPages = Math.ceil(total / pageSize);
const renderPaginationRange = () => {
const totalNumbersToShow = 7;
if (totalNumbersToShow > totalPages) {
return Array.from({ length: totalPages }, (_, index) => index + 1);
}
const leftIndex = Math.max(currentPage - 1, 1);
const rightIndex = Math.min(currentPage + 1, totalPages);
const showLeftEllipsis = leftIndex > 3;
const showRightEllipsis = rightIndex < totalPages - 2;
const itemCount = 5;
if (!showLeftEllipsis && showRightEllipsis) {
const leftRange = range(1, itemCount + 1);
return [...leftRange, -1, totalPages];
} else if (showLeftEllipsis && !showRightEllipsis) {
const rightRange = range(totalPages - itemCount + 1, totalPages + 1);
return [1, -2, ...rightRange];
} else {
const middleRange = range(leftIndex, rightIndex + 1);
return [1, -1, ...middleRange, -2, totalPages];
}
};
return (
<>
{renderPaginationRange().map((page) => {
if (page === -1 || page === -2) {
return <span key={page}>...</span>;
}
return (
<button
key={page}
onClick={() => handlePageChange(page)}
disabled={currentPage === page}
>
{page}
</button>
);
})}
</>
);
};
testing is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.