Blog>
Snippets

Adding Pagination to React TanStack Table

Integrate pagination functionality into React TanStack Table using the usePagination hook, including setup for page size and navigation controls.
import { useReactTable, usePagination } from '@tanstack/react-table'
Import necessary hooks from TanStack Table library.
const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
  getPaginationRowModel: getPaginationRowModel()
})
Initialize useReactTable hook with pagination.
const { pageIndex, pageSize, setPageIndex, setPageSize, pageCount } = table
Destructure pagination-related properties and setters from the table instance.
<div>
  <button onClick={() => setPageIndex(0)} disabled={!table.getCanPreviousPage()}>First</button>
  <button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>Previous</button>
  <button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>Next</button>
  <button onClick={() => setPageIndex(pageCount - 1)} disabled={!table.getCanNextPage()}>Last</button>
</div>
Render pagination controls to navigate through the table pages.
<div>
  <select value={pageSize} onChange={e => setPageSize(Number(e.target.value))}>
    {[10, 20, 30, 40, 50].map(pageSize => (
      <option key={pageSize} value={pageSize}>{pageSize}</option>
    ))}
  </select>
</div>
Render a select dropdown for changing the page size.