-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPagination.js
94 lines (76 loc) · 2.14 KB
/
Pagination.js
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
import React, { useEffect } from "react";
import './App.css';
function App() {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const fetchData = async () => {
const apiUrl = "https://jsonplaceholder.typicode.com/todos/";
setLoading(true);
const getJsonData = await fetch(apiUrl);
setData(await getJsonData.json());
setLoading(false);
}
useEffect(() => {
fetchData();
}, []);
// Pagination
const [currentPage, setCurrentPage] = React.useState(1);
const recordsPerPage = 5;
const lastIndex = currentPage * recordsPerPage;
const firstIndex = lastIndex - recordsPerPage;
const records = data.slice(firstIndex, lastIndex);
const nPage = Math.ceil(data.length / recordsPerPage);
const numbers = Array.from({ length: nPage }, (_item, index) => index + 1);
// or
// [...Array(nPage + 1).keys()].slice(1);
console.log("data: ", data);
const prevFunc = () => {
if (currentPage !== 1) {
setCurrentPage(currentPage - 1);
}
}
const nextFunc = () => {
if (currentPage !== nPage) {
setCurrentPage(currentPage + 1);
}
}
const changeCPage = (id) => {
setCurrentPage(id);
}
if(loading) return "Loading...";
return (
<div className="App">
<table>
<tr>
<td>ID</td>
<td>User ID</td>
<td>Title</td>
<td>Completed</td>
</tr>
{records?.map((d, index) => (
<tr key={index}>
<td>{d?.id}</td>
<td>{d?.userId}</td>
<td>{d?.title}</td>
<td>{String(d?.completed)}</td>
</tr>
))}
</table>
{/*
CSS styles
ul > li {
display: inline-block
} */}
<ul>
<li><span onClick={prevFunc}>Prev</span></li>
{
numbers?.map(n => (
<li className={currentPage === n ? "active" : ""}><span onClick={() => changeCPage(n)}>{n}</span></li>
))
}
<li><span onClick={nextFunc}>Next</span></li>
</ul>
</div>
);
}
export default App;