/
Pagination.tsx
129 lines (113 loc) · 2.76 KB
/
Pagination.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { range } from "lodash";
import ArrowButton from "./ArrowButton";
import PageButton from "./PageButton";
interface Prop {
id: string,
pageNo: number;
perPage: number;
totalCount: number;
onChangePageNo: (page: number) => void
}
const Pagination: React.FC<Prop> = ({
id,
pageNo,
perPage,
totalCount,
onChangePageNo,
}: Prop) => {
const pageSize = Math.ceil(totalCount / perPage) || 1;
const hasPrev = pageNo > 1;
const hasNext = pageNo < pageSize;
const createPageNumbers = (): number[] => {
const max = 9;
const normalLimit = 4;
const expandedLimit = 2;
const pageSizeWithinMax = pageSize >= 1 && pageSize <= max;
const createLimit = (): number => {
if (pageSizeWithinMax) {
return pageSize;
}
if (pageNo <= normalLimit || pageNo + normalLimit > pageSize) {
return normalLimit;
}
return expandedLimit;
};
const limit = createLimit();
const first = range(1, limit + 1);
const middle = range(pageNo - 1, pageNo + 2);
const last = range(pageSize - limit + 1, pageSize + 1);
const createNumbers = (): number[] => {
if (pageSizeWithinMax) {
return [...first];
}
if (limit === normalLimit) {
return [...first, -1, ...last];
}
return [...first, -1, ...middle, -2, ...last];
};
return createNumbers();
};
const onChangePageButton = (page: number): void => {
if (page > 0) {
onChangePageNo(page);
}
};
const onClickLeftArrowButton = (): void => {
if (pageNo > 1) {
onChangePageNo(pageNo - 1);
}
};
const onClickRightArrowButton = (): void => {
if (pageNo < totalCount) {
onChangePageNo(pageNo + 1);
}
};
return (
<div
className="
mt-[2.5rem]
mb-[1rem]
flex
h-[2.5rem]
flex-row
items-center
justify-center
max-[570px]:flex-col"
>
<ArrowButton
text="Prev"
direction="left"
onClick={onClickLeftArrowButton}
disabled={!hasPrev}
/>
<div
className="
mx-[2.8rem]
flex
h-[2.5rem]
flex-row
items-center
justify-center
gap-[0.1rem]"
>
{createPageNumbers().map((page: number) => (
<PageButton
id={`${id}pageButtonId${page}`}
key={`${id}pageButtonKey${page}`}
name={`${id}pageButtonName`}
pageNo={pageNo}
value={page}
onChange={() => onChangePageButton(page)}
/>
))}
</div>
<ArrowButton
text="Next"
direction="right"
onClick={onClickRightArrowButton}
disabled={!hasNext}
/>
</div>
);
};
export default Pagination;