Implementing Basic Pagination with React TanStack Table
Showcase how to set up basic pagination in a table using React TanStack Table, including managing state for the current page and page size.
import React, { useState } from 'react';
import { useTable, usePagination } from 'react-table';
First, import necessary hooks from react-table.
const Table = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we use page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: { pageIndex, pageSize },
} = useTable(
{
columns,
data,
initialState: { pageIndex: 0 }, // Start with first page
},
usePagination
);
Setting up the table component with pagination controlled by useTable and usePagination hooks.
return (
<div>
<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 structure including the header and body by mapping through headerGroups and page for rows.
<div className='pagination'>
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>{'<<'}</button>
<button onClick={() => previousPage()} disabled={!canPreviousPage}>{'<'}</button>
<button onClick={() => nextPage()} disabled={!canNextPage}>{'>'}</button>
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>{'>>'}</button>
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>
</span>
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value));
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
</div>
);
};
Rendering pagination controls and selecting page size. Utilizes controlled component behavior to navigate and determine page size.