Blog>
Snippets

Initializing a Basic React Table with TanStack

Shows how to set up a basic table component in React using the TanStack Table library, defining columns and passing data.
import { createColumnHelper, useReactTable } from '@tanstack/react-table';
import React from 'react';
import { defaultData } from './data.json';
Imports the necessary functions from the TanStack Table library and the data from a JSON file.
const columnHelper = createColumnHelper();
Initializes the column helper function which is used to define the table columns.
const columns = [
  columnHelper.accessor('id', {
    cell: info => info.getValue(),
    header: () => <span>ID</span>,
  }),
  columnHelper.accessor('name', {
    cell: info => info.getValue(),
    header: () => <span>Name</span>,
  }),
];
Defines the columns for the table, including how to display the 'ID' and 'Name' fields.
function Table() {
  const table = useReactTable({
    columns,
    data: defaultData,
  });
  return (
    <table>
      <thead>
      {table.getHeaderGroups().map(headerGroup => (
        <tr key={headerGroup.id}>
          {headerGroup.headers.map(header => (
            <th key={header.id}>{header.isPlaceholder ? null : header.renderHeader()}</th>
          ))}
        </tr>
      ))}
      </thead>
      <tbody>
      {table.getRowModel().rows.map(row => {
        table.prepareRow(row);
        return (
          <tr key={row.id}>
            {row.getVisibleCells().map(cell => (
              <td key={cell.id}>{cell.renderCell()}</td>
            ))}
          </tr>
        );
      })}
      </tbody>
    </table>
  );
}
Creates the table component using the 'useReactTable' hook, defining how to render the header and the body with the data.