-
Notifications
You must be signed in to change notification settings - Fork 0
/
ComplexPaginationContainer.jsx
93 lines (84 loc) · 2.42 KB
/
ComplexPaginationContainer.jsx
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
import { useLoaderData, useLocation, useNavigate } from 'react-router-dom';
const ComplexPaginationContainer = () => {
const { meta } = useLoaderData();
const { pageCount, page } = meta.pagination;
const { search, pathname } = useLocation();
const navigate = useNavigate();
const handlePageChange = (pageNumber) => {
const searchParams = new URLSearchParams(search);
searchParams.set('page', pageNumber);
navigate(`${pathname}?${searchParams.toString()}`);
};
const addPageButton = ({ pageNumber, activeClass }) => {
return (
<button
key={pageNumber}
onClick={() => handlePageChange(pageNumber)}
className={`btn btn-xs sm:btn-md border-none join-item ${
activeClass ? 'bg-base-300 border-base-300 ' : ''
}`}
>
{pageNumber}
</button>
);
};
const renderPageButtons = () => {
const pageButtons = [];
// first button
pageButtons.push(addPageButton({ pageNumber: 1, activeClass: page === 1 }));
// dots
if (page > 2) {
pageButtons.push(
<button className='join-item btn btn-xs sm:btn-md' key='dots-1'>
...
</button>
);
}
// active/current page
if (page !== 1 && page !== pageCount) {
pageButtons.push(addPageButton({ pageNumber: page, activeClass: true }));
}
// dots
if (page < pageCount - 1) {
pageButtons.push(
<button className='join-item btn btn-xs sm:btn-md' key='dots-2'>
...
</button>
);
}
// last button
pageButtons.push(
addPageButton({ pageNumber: pageCount, activeClass: page === pageCount })
);
return pageButtons;
};
if (pageCount < 2) return null;
return (
<div className='mt-16 flex justify-end'>
<div className='join'>
<button
className='btn btn-xs sm:btn-md join-item'
onClick={() => {
let prevPage = page - 1;
if (prevPage < 1) prevPage = pageCount;
handlePageChange(prevPage);
}}
>
Prev
</button>
{renderPageButtons()}
<button
className='btn btn-xs sm:btn-md join-item'
onClick={() => {
let nextPage = page + 1;
if (nextPage > pageCount) nextPage = 1;
handlePageChange(nextPage);
}}
>
Next
</button>
</div>
</div>
);
};
export default ComplexPaginationContainer;