Blog>
Snippets

Basic Setup of TanStack Table

Demonstrate how to implement a basic TanStack Table in React, including setting up columns and rendering basic row data.
import React from 'react';
import {
  createColumnHelper,
  useReactTable,
} from '@tanstack/react-table';
Import necessary utilities from TanStack Table library.
const columnHelper = createColumnHelper();
Initialize the column helper to define and manage table columns.
const defaultColumns = [
  columnHelper.accessor('id', {
    header: () => 'ID',
    cell: info => info.getValue()
  }),
  columnHelper.accessor('name', {
    header: () => 'Name',
    cell: info => info.getValue()
  })
];
Define table columns using the column helper, including ID and Name columns.
const data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
Sample data to display in the table.
function MyTable() {
  const table = useReactTable({
    data,
    columns: defaultColumns
  });

  return (
    <div>
      <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 => (
            <tr key={row.id}>
              {row.getVisibleCells().map(cell => (
                <td key={cell.id}>{cell.renderCell()}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
React component rendering the table with defined columns and data using TanStack Table.