Enabling Pagination in React Table with TanStack
Illustrates the process of adding pagination controls to a React Table, using the usePagination hook for client-side data management.
import { useTable, usePagination } from '@tanstack/react-table';
Importing required hooks from @tanstack/react-table package.
const Table = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we use page, which is managed with usePagination
canPreviousPage,
canNextPage,
nextPage,
previousPage,
pageCount,
gotoPage,
pageIndex
} = useTable({ columns, data }, usePagination);
Setting up the table component with useTable and usePagination hooks. Here, 'page' contains the current page rows.
// Table Markup
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
Rendering the table markup with header and body, iterating over 'page' for the body rows.
// Pagination Controls
<div>
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>{'<<'}</button>
<button onClick={() => previousPage()} disabled={!canPreviousPage}>{'<'}</button>
<span>
Page {' '}
{pageIndex + 1} of {pageCount}
</span>
<button onClick={() => nextPage()} disabled={!canNextPage}>{'>'}</button>
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>{'>>'}</button>
</div>
</>
);
};
Adding pagination controls below the table, enabling navigation through the dataset.