|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import { |
| 3 | + Pagination, |
| 4 | + PaginationEllipsis, |
| 5 | + PaginationContent, |
| 6 | + PaginationLink, |
| 7 | + PaginationNext, |
| 8 | + PaginationPrevious, |
| 9 | + PaginationItem, |
| 10 | +} from '../ui/pagination'; |
| 11 | + |
| 12 | +type PaginationProps = React.ComponentProps<typeof Pagination> & { |
| 13 | + allItems: number; |
| 14 | + itemsPerPage: number; |
| 15 | + initialPage?: number; |
| 16 | +}; |
| 17 | + |
| 18 | +export default function UIPagination({ allItems, itemsPerPage, initialPage = 1, ...rest }: PaginationProps) { |
| 19 | + const totalPages = Math.ceil(allItems / itemsPerPage); |
| 20 | + const [currentPage, setCurrentPage] = useState(initialPage); |
| 21 | + |
| 22 | + const handlePrevious = () => { |
| 23 | + setCurrentPage((prev) => Math.max(1, prev - 1)); |
| 24 | + }; |
| 25 | + |
| 26 | + const handleNext = () => { |
| 27 | + setCurrentPage((prev) => Math.min(totalPages, prev + 1)); |
| 28 | + }; |
| 29 | + |
| 30 | + const renderPageNumbers = () => { |
| 31 | + const pageNumbers = []; |
| 32 | + |
| 33 | + let startPage = Math.max(1, currentPage - 1); |
| 34 | + let endPage = startPage + 2; |
| 35 | + |
| 36 | + if (endPage > totalPages) { |
| 37 | + endPage = totalPages; |
| 38 | + startPage = Math.max(1, endPage - 2); |
| 39 | + } |
| 40 | + |
| 41 | + if (startPage > 1) { |
| 42 | + pageNumbers.push( |
| 43 | + <PaginationItem key="start-ellipsis"> |
| 44 | + <PaginationEllipsis /> |
| 45 | + </PaginationItem>, |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + for (let i = startPage; i <= endPage; i++) { |
| 50 | + pageNumbers.push( |
| 51 | + <PaginationItem key={i}> |
| 52 | + <PaginationLink |
| 53 | + href="#" |
| 54 | + onClick={(e) => { |
| 55 | + e.preventDefault(); |
| 56 | + setCurrentPage(i); |
| 57 | + }} |
| 58 | + isActive={i === currentPage} |
| 59 | + > |
| 60 | + {i} |
| 61 | + </PaginationLink> |
| 62 | + </PaginationItem>, |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + if (endPage < totalPages) { |
| 67 | + pageNumbers.push( |
| 68 | + <PaginationItem key="end-ellipsis"> |
| 69 | + <PaginationEllipsis /> |
| 70 | + </PaginationItem>, |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + return pageNumbers; |
| 75 | + }; |
| 76 | + |
| 77 | + return ( |
| 78 | + <Pagination {...rest}> |
| 79 | + <PaginationContent> |
| 80 | + <PaginationItem> |
| 81 | + <PaginationPrevious href="#" onClick={handlePrevious} /> |
| 82 | + </PaginationItem> |
| 83 | + |
| 84 | + {renderPageNumbers()} |
| 85 | + |
| 86 | + <PaginationItem> |
| 87 | + <PaginationNext href="#" onClick={handleNext} /> |
| 88 | + </PaginationItem> |
| 89 | + </PaginationContent> |
| 90 | + </Pagination> |
| 91 | + ); |
| 92 | +} |
0 commit comments