Created
March 15, 2023 20:10
-
-
Save ArthurDias01/11d65b3e6e65a55b26a91bbdb5442b38 to your computer and use it in GitHub Desktop.
Pagination - Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PaginationItem } from "./PaginationItem"; | |
interface PaginationProps { | |
totalCountOfRegisters: number; | |
registersPerPage?: number; | |
currentPage?: number; | |
onPageChange: (page: number) => void; | |
} | |
const siblingsCount = 2; | |
function generatePagesArray(from: number, to: number) { | |
return [...new Array(to - from)].map( | |
(_, index) => { | |
return from + index + 1 | |
}).filter((page) => page > 0) //filtro pra retirar páginas calculadas com índices negativos | |
} | |
export const Pagination = ({ | |
totalCountOfRegisters, | |
registersPerPage = 20, | |
currentPage = 1, | |
onPageChange, | |
}: PaginationProps) => { | |
const lastPage = Math.ceil(totalCountOfRegisters / registersPerPage); | |
const previousPages = currentPage > 1 | |
? generatePagesArray(currentPage - 1 - siblingsCount, currentPage - 1) | |
: [] | |
const nextPages = currentPage < lastPage | |
? generatePagesArray(currentPage, Math.min(currentPage + siblingsCount, lastPage)) | |
: [] | |
return ( | |
<div className="btn-group self-center leading-relaxed my-8"> | |
{/* <div className="flex items-center h-fit mt-3 mx-3"> | |
<strong>{currentPage === 1 ? 1 : (currentPage - 1) * registersPerPage + 1} </strong> | |
<strong>{'\xa0a '}{currentPage * registersPerPage > totalCountOfRegisters ? totalCountOfRegisters : currentPage * registersPerPage} | |
</strong> | |
<strong className="ml-1"> de {totalCountOfRegisters} total</strong> | |
</div> */} | |
{currentPage > (1 + siblingsCount) && ( | |
<> | |
<PaginationItem key={1} number={1} onPageChange={onPageChange} /> | |
{currentPage > (2 + siblingsCount) && | |
<button className="btn btn-disabled items-center justify-center">...</button> | |
} | |
</> | |
)} | |
{previousPages.length > 0 && previousPages.map(page => { | |
return <PaginationItem key={page} number={page} onPageChange={onPageChange} /> | |
})} | |
<PaginationItem number={currentPage} isCurrent onPageChange={onPageChange} /> | |
{nextPages.length > 0 && nextPages.map(page => { | |
return <PaginationItem key={page} number={page} onPageChange={onPageChange} /> | |
})} | |
{currentPage + siblingsCount < lastPage && ( | |
<> | |
{currentPage + 1 + siblingsCount < lastPage && | |
<button className="btn btn-disabled items-center justify-center text-neutral1">...</button>} | |
<PaginationItem key={lastPage} number={lastPage} onPageChange={onPageChange} /> | |
</> | |
)} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment