I’m learning to create data tables for a ReactJS / NextJS application without libraries.
I’m having a hard time paginating the table, can you please provide a code sample to handle this.
This is the table code I used:
JavaScript
x
40
40
1
const Table = () => {
2
3
const data = [
4
{name: 'Rara', profile: 'profile1', comment: 'comra'},
5
{name: 'Dada', profile: 'profile2', comment: 'comda'},
6
{name: 'Gaga', profile: 'profile1', comment: 'comga'},
7
{name: 'Mama', profile: 'profile3', comment: 'comma'},
8
{name: 'Papa', profile: 'profile4', comment: 'compa'},
9
// ...
10
]
11
12
const columns = [
13
{ id: 1, title: "Name", accessor: "name" },
14
{ id: 2, title: "Profile", accessor: "profile" },
15
{ id: 3, title: "Comment", accessor: "comment" },
16
];
17
18
return (
19
<table className={styles.container}>
20
<thead>
21
<tr>
22
{columns.map((col) => (
23
<th key={col.id}>{col.title}</th>
24
))}
25
</tr>
26
</thead>
27
<tbody>
28
{data.map((user, i) => (
29
<tr key={i}>
30
{columns.map((col) => (
31
<td key={col.id}>{user[col.accessor]}</td>
32
))}
33
</tr>
34
))}
35
</tbody>
36
</table>
37
);
38
};
39
40
I really appreciate any answer.
Advertisement
Answer
Use Array#slice
with an incremented page
state. Something like this should get you started:
JavaScript
1
30
30
1
const Table = () => {
2
3
// .....
4
5
const itemsPerPage = 10;
6
const [page, setPage] = useState(1);
7
const displayData = useMemo(() => {
8
const start = (page - 1) * itemsPerPage;
9
return data.slice(start, start + itemsPerPage);
10
}, [data]);
11
12
// .....
13
14
return (
15
<>
16
<button onClick={() => setPage(page + 1)}> Next Page </button>
17
<button onClick={() => setPage(page - 1)}> Prev Page </button>
18
19
{ /* ..... */ }
20
21
<tbody>
22
{displayData.map((user, i) => (
23
24
{ /* ..... */ }
25
26
27
</>
28
);
29
};
30