Blog>
Snippets

Using CSS Flexbox for Responsive Column Widths

Demonstrate how to apply CSS Flexbox properties to TanStack Table columns to achieve responsive column sizes without the need for JavaScript.
import { useTable } from 'react-table';

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

  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div {...getTableProps()} style={{ display: 'flex', flexDirection: 'column', overflowX: 'auto' }}>
        {headerGroups.map(headerGroup => (
          <div {...headerGroup.getHeaderGroupProps()} style={{ display: 'flex' }}>
            {headerGroup.headers.map(column => (
              <div {...column.getHeaderProps()} style={{ flexGrow: 1, flexBasis: 0, textAlign: 'left' }}>
                {column.render('Header')}
              </div>
            ))}
          </div>
        ))}
        <div {...getTableBodyProps()}>
          {rows.map(row => {
            prepareRow(row);
            return (
              <div {...row.getRowProps()} style={{ display: 'flex' }}>
                {row.cells.map(cell => (
                  <div {...cell.getCellProps()} style={{ flexGrow: 1, flexBasis: 0, textAlign: 'left' }}>
                    {cell.render('Cell')}
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
This code creates a table using TanStack Table and applies CSS Flexbox for responsive column widths. The flex container is set on the table and each row, with columns set to grow and shrink equally. This avoids the need for JavaScript-based resizing, offering a CSS-only solution for responsive tables.