Blog>
Snippets

Integrating Pagination with React TanStack Table

Illustrates the steps to implement pagination in a table by leveraging the usePagination hook, including UI controls for navigation.
import { useTable, usePagination } from 'react-table';
Firstly, import usePagination along with useTable from react-table to manage pagination.
function Table({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    canPreviousPage,
    canNextPage,
    nextPage,
    previousPage,
    state: { pageIndex, pageSize }
  } = useTable(
    {
      columns,
      data
    },
    usePagination
  );
}
Define the Table component. usePagination hook integrates pagination by enhancing the useTable hook with necessary pagination controls.
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>
    <div>
      <button onClick={() => previousPage()} disabled={!canPreviousPage}>
        Previous
      </button>
      <button onClick={() => nextPage()} disabled={!canNextPage}>
        Next
      </button>
    </div>
  </>
);
Render the table with pagination controls. The page array contains rows for the current page. Navigation buttons are enabled or disabled based on canPreviousPage and canNextPage.