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:
const Table = () => {
const data = [
{name: 'Rara', profile: 'profile1', comment: 'comra'},
{name: 'Dada', profile: 'profile2', comment: 'comda'},
{name: 'Gaga', profile: 'profile1', comment: 'comga'},
{name: 'Mama', profile: 'profile3', comment: 'comma'},
{name: 'Papa', profile: 'profile4', comment: 'compa'},
// ...
]
const columns = [
{ id: 1, title: "Name", accessor: "name" },
{ id: 2, title: "Profile", accessor: "profile" },
{ id: 3, title: "Comment", accessor: "comment" },
];
return (
<table className={styles.container}>
<thead>
<tr>
{columns.map((col) => (
<th key={col.id}>{col.title}</th>
))}
</tr>
</thead>
<tbody>
{data.map((user, i) => (
<tr key={i}>
{columns.map((col) => (
<td key={col.id}>{user[col.accessor]}</td>
))}
</tr>
))}
</tbody>
</table>
);
};
I really appreciate any answer.
Advertisement
Answer
Use Array#slice with an incremented page state. Something like this should get you started:
const Table = () => {
// .....
const itemsPerPage = 10;
const [page, setPage] = useState(1);
const displayData = useMemo(() => {
const start = (page - 1) * itemsPerPage;
return data.slice(start, start + itemsPerPage);
}, [data]);
// .....
return (
<>
<button onClick={() => setPage(page + 1)}> Next Page </button>
<button onClick={() => setPage(page - 1)}> Prev Page </button>
{ /* ..... */ }
<tbody>
{displayData.map((user, i) => (
{ /* ..... */ }
</>
);
};