Blog>
Snippets

Implementing Pagination with TanStack Table

Illustrate the setup required to add pagination controls to a data table, utilizing the usePagination hook from the TanStack Table library.
import { useReactTable, getPaginationRowModel } from '@tanstack/react-table';
Import necessary hooks and functions from TanStack Table.
const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
  getPaginationRowModel: getPaginationRowModel(),
});
Initialize the table with data, columns, and enable pagination model.
const { setPageIndex, getPageCount, getCanPreviousPage, getCanNextPage, nextPage, previousPage } = table;
Destructure methods from the table instance for managing pagination.
<button onClick={() => previousPage()} disabled={!getCanPreviousPage()}>Previous</button>
Create a 'Previous' button with a click event that moves to the previous page, disabled when there are no more previous pages.
<button onClick={() => nextPage()} disabled={!getCanNextPage()}>Next</button>
Create a 'Next' button with a click event that moves to the next page, disabled when there are no more next pages.
<div>Page {table.getState().pagination.pageIndex + 1} of {getPageCount()}</div>
Display current page number and total page count.