Blog>
Snippets

Configuring Basic Columns in TanStack Table

Demonstrate how to define basic columns in TanStack Table, including setting headers and accessing row values.
const columns = [
  { header: 'Name', accessorKey: 'name' },
  { header: 'Age', accessorKey: 'age' },
  { header: 'Company', accessorKey: 'company' },
  { header: 'Twitter', accessorKey: 'twitter' }
];
Defines the column structure for the TanStack Table. Each column is defined by an object that includes a 'header' property for the column title and an 'accessorKey' that specifies the key from the data object to be displayed in the column.
const table = useReactTable({
  columns,
  data
});
Initializes the TanStack Table using the 'useReactTable' hook by passing the previously defined columns and the data array. This prepares the table for rendering.
<table>
  <thead>
    {table.getHeaderGroups().map(headerGroup => (
      <tr key={headerGroup.id}>
        {headerGroup.headers.map(header => (
          <th key={header.id}>{header.renderHeader()}</th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody>
    {table.getRowModel().rows.map(row => (
      <tr key={row.id}>
        {row.getVisibleCells().map(cell => (
          <td key={cell.id}>{cell.renderCell()}</td>
        ))}
      </tr>
    ))}
  </tbody>
</table>
Renders the table element using the data prepared by TanStack Table. It iterates through header groups to render table headers and through rows and their visible cells to render the table body. Each header and cell content is obtained by calling the render function provided by the library.