Blog>
Snippets

Implementing Basic Row Pinning

Demonstrate how to pin a row to the top of the React TanStack Table using a simple toggle mechanism in the table's configuration.
import { useTable } from '@tanstack/react-table';
Import useTable hook from '@tanstack/react-table' to create and manage the table.
const columns = React.useMemo(() => [
  { accessorKey: 'id', header: 'ID' },
  { accessorKey: 'name', header: 'Name' }
], []);
Define the columns for the table. For simplicity, we use 'id' and 'name'.
const data = React.useMemo(() => [
  { id: 1, name: 'Row 1' },
  { id: 2, name: 'Row 2' },
  // Add more rows as needed
], []);
Define the data for the table. Each row object must align with the defined columns.
const [pinnedRows, setPinnedRows] = React.useState([]);
Utilize useState to keep track of the IDs of the rows that are pinned.
const tableInstance = useTable({
  columns,
  data,
  getRowId: row => row.id,
  state: { pinnedRows },
  onPinRow: rowId => {
    setPinnedRows(prev =>
      prev.includes(rowId) ? prev.filter(id => id !== rowId) : [...prev, rowId]
    );
  }
});
Create the table instance with useTable hook. The state includes pinnedRows. The onPinRow function toggles the pin state of a row by ID.
const { getTableProps, getTableBodyProps, rows, prepareRow } = tableInstance;
Destructure methods and properties from the table instance for rendering.
return (
  <table {...getTableProps()}>
    <tbody {...getTableBodyProps()}>
      {rows.map(row => {
        prepareRow(row);
        return (
          <tr {...row.getRowProps()}>
            {row.cells.map(cell => (
              <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
            ))}
            <td>
              <button onClick={() => tableInstance.onPinRow(row.original.id)}>
                {pinnedRows.includes(row.original.id) ? 'Unpin' : 'Pin'}
              </button>
            </td>
          </tr>
        );
      })}
    </tbody>
  </table>
);
Render the table with rows. Each row includes a 'Pin/Unpin' button to toggle its pin state. Rows are sorted to respect pinned rows ordering.