Blog>
Snippets

Setting Up Basic Pagination with TanStack Table

Demonstrate how to set up basic client-side pagination in a React app using the TanStack Table library, including configuration of the pagination state and useTable hook.
import React from 'react';
import { useTable, usePagination } from '@tanstack/table';
Import the required hooks from TanStack Table and React.
const TableComponent = ({ columns, data }) => {
  const tableInstance = useTable({
    columns,
    data,
  },
  usePagination);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    canPreviousPage,
    canNextPage,
    nextPage,
    previousPage,
    state: { pageIndex, pageSize },
  } = tableInstance;

  return (
    // Table JSX
  );
};
Defines a TableComponent which utilizes useTable and usePagination hooks from TanStack Table to create a paginated table.
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>
    <div>
      <button onClick={() => previousPage()} disabled={!canPreviousPage}>Previous</button>
      <button onClick={() => nextPage()} disabled={!canNextPage}>Next</button>
    </div>
  </div>
);
Renders the table with pagination controls. It maps over headerGroups and page rows to structure the table HTML. Previous and next page buttons are included with their respective functionality.