Blog>
Snippets

Implementing Basic Sticky Columns Using CSS

Showcase how to make a column sticky in React TanStack Table using CSS properties such as `position: sticky;` and `left: 0;` to lock the first column in place during horizontal scroll.
import { useTable } from '@tanstack/react-table';

function Table({ columns, data }) {
  const tableInstance = useTable({
    columns,
    data
  });
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = tableInstance;

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              // Apply sticky CSS class to the first column header
              <th {...column.getHeaderProps()} className={column.id === 'yourColumnId' ? 'stickyColumn' : ''}>
                {column.render('Header')}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                // Apply sticky CSS class to the first column cells
                return <td {...cell.getCellProps()} className={cell.column.id === 'yourColumnId' ? 'stickyColumn' : ''}>{cell.render('Cell')}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
This code sets up a basic React component using the TanStack Table (formerly known as React Table). It applies a sticky CSS class to the first column's header and cells. Replace 'yourColumnId' with the actual ID of the column you want to make sticky. You need to define the .stickyColumn class in your stylesheet with `position: sticky;` and `left: 0;` to actually make the column sticky.