|
| 1 | +import { useMemo } from 'react'; |
| 2 | + |
| 3 | +export function usePagination( |
| 4 | + currentPage: number, |
| 5 | + totalPages: number, |
| 6 | + setPage: (page: number) => void |
| 7 | +) { |
| 8 | + const maxPageButtons = 5; |
| 9 | + const currentGroup = Math.floor((currentPage - 1) / maxPageButtons); |
| 10 | + const startPage = currentGroup * maxPageButtons + 1; |
| 11 | + const endPage = Math.min(startPage + maxPageButtons - 1, totalPages); |
| 12 | + |
| 13 | + const paginationButtons = useMemo( |
| 14 | + () => |
| 15 | + [ |
| 16 | + { label: '<<', page: 1, isNav: true, disabled: currentPage === 1 }, |
| 17 | + { |
| 18 | + label: '<', |
| 19 | + page: Math.max(startPage - 1, 1), |
| 20 | + isNav: true, |
| 21 | + disabled: currentPage === 1, |
| 22 | + }, |
| 23 | + ...Array.from({ length: endPage - startPage + 1 }).map((_, idx) => ({ |
| 24 | + label: (startPage + idx).toString(), |
| 25 | + page: startPage + idx, |
| 26 | + isNav: false, |
| 27 | + disabled: currentPage === startPage + idx, |
| 28 | + })), |
| 29 | + { |
| 30 | + label: '>', |
| 31 | + page: Math.min(startPage + maxPageButtons, totalPages), |
| 32 | + isNav: true, |
| 33 | + disabled: currentPage === totalPages, |
| 34 | + }, |
| 35 | + { |
| 36 | + label: '>>', |
| 37 | + page: totalPages, |
| 38 | + isNav: true, |
| 39 | + disabled: currentPage === totalPages, |
| 40 | + }, |
| 41 | + ].map(({ label, page, isNav, disabled }) => ( |
| 42 | + <button |
| 43 | + key={label} |
| 44 | + onClick={() => !disabled && setPage(page)} |
| 45 | + disabled={disabled} |
| 46 | + className={`rounded-md border px-3 py-1 transition ${ |
| 47 | + disabled |
| 48 | + ? isNav |
| 49 | + ? 'text-gray-400' // <<, <, >, >> 버튼이 비활성화되면 글씨만 회색 |
| 50 | + : 'bg-gray-900 text-white underline' // 페이지 번호 버튼이 비활성화되면 배경 변경 |
| 51 | + : currentPage === page |
| 52 | + ? 'bg-black font-bold text-white underline' // 현재 페이지 버튼 스타일 |
| 53 | + : 'bg-white hover:bg-gray-100' // 기본 버튼 스타일 |
| 54 | + }`} |
| 55 | + > |
| 56 | + {label} |
| 57 | + </button> |
| 58 | + )), |
| 59 | + [currentPage, endPage, setPage, startPage, totalPages] |
| 60 | + ); |
| 61 | + |
| 62 | + return { paginationButtons, goToPage: setPage }; |
| 63 | +} |
0 commit comments