Blog>
Snippets

Initializing a React TanStack Table with Full-Width and Resizable Columns

Set up a basic React TanStack Table component and configure it to have full-width and resizable columns using useBlockLayout and useResizeColumns hooks.
import { useTable, useBlockLayout, useResizeColumns } from '@tanstack/react-table';
import { useMemo } from 'react';
Imports necessary hooks from TanStack Table and React.
const defaultColumn = useMemo(() => ({
  minWidth: 30, // The minimum width of each column
  width: 150, // The initial width of each column
  maxWidth: 400, // The maximum width of each column
}), []);
Setups the defaultColumn to manage minWidth, width, and maxWidth for all columns.
const data = useMemo(() => [...], []); // Your data array here
Initializes memoized data for the table.
const columns = useMemo(
  () => [
    // Define your columns here
    { header: 'Column 1', accessorKey: 'col1' },
    { header: 'Column 2', accessorKey: 'col2' }
  ],
  []
);
Creates a memoized columns setup with given headers and accessor keys.
const tableInstance = useTable({
  data,
  columns,
  defaultColumn,
  getCoreRowModel: getCoreRowModel(),
  getTableProps: useBlockLayout,
  getHeaderGroupProps: useResizeColumns,
});
Initializes the table instance with the data, columns, layout, and resize hooks.
// Component to render the table
function Table() {
  const {
    getTableProps,
    getHeaderGroupProps,
    headers,
    rows,
    prepareRow,
  } = tableInstance;

  return (
    <table {...getTableProps()} style={{ width: '100%' }}>
      <thead>
        {headers.map(header => (
          <th {...header.getHeaderProps()}>{header.render('Header')}</th>
        ))}
      </thead>
      <tbody>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
Defines a Table component to render the table using properties and methods from the table instance.