Blog>
Snippets

Setting Up Pagination in TanStack Table

Provide an example of setting up client-side pagination in TanStack Table, including configuring page size and navigation.
import { useReactTable } from '@tanstack/react-table';
First, import `useReactTable` from '@tanstack/react-table' to create a table instance.
const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
  getPaginationRowModel: getPaginationRowModel()
});
Initialize the table with data, and columns, and enable pagination models.
const [pageIndex, setPageIndex] = useState(0);
const [pageSize, setPageSize] = useState(10);
Create state for controlling the current page index and page size.
useEffect(() => {
  table.setPageIndex(pageIndex);
}, [pageIndex, table]);
Use an effect to synchronize the table's page index state with the local state.
useEffect(() => {
  table.setPageSize(pageSize);
}, [pageSize, table]);
Use an effect to set the table's page size based on the local state.
<button onClick={() => setPageIndex(0)}>First Page</button>
<button onClick={() => setPageIndex(old => Math.max(old - 1, 0))}>Previous</button>
<button onClick={() => setPageIndex(old => (!table.getPageCount() || old === table.getPageCount() - 1) ? old : old + 1)}>Next</button>
<button onClick={() => setPageIndex(table.getPageCount() - 1)}>Last Page</button>
Pagination controls for navigating pages. Buttons for moving to the first, previous, next, and last pages.
<select
  value={pageSize}
  onChange={e => setPageSize(parseInt(e.target.value, 10))}
>
  {[10, 20, 30, 40, 50].map(size => (
    <option key={size} value={size}>{size} Rows</option>
  ))}
</select>
Dropdown for selecting the page size. On change, it updates the page size state.