Blog>
Snippets

Defining a Simple Row Model in TanStack Table

Demonstrate how to define a basic row model in TanStack Table and render a simple table component.
import { useReactTable } from '@tanstack/react-table';
Imports the useReactTable hook from @tanstack/react-table.
const columns = [
  { accessorKey: 'id', header: 'ID' },
  { accessorKey: 'name', header: 'Name' },
  { accessorKey: 'age', header: 'Age' }
];
Defines the column schema for the table, including the key and header name for each column.
const data = [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: 24 },
  { id: 3, name: 'Charlie', age: 28 }
];
Defines the data to display in the table as an array of objects.
const tableInstance = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel()
});
Creates a new table instance using the useReactTable hook, passing in the data, columns, and the getCoreRowModel function to manage rows.
return (
  <table>
    <thead>
      {tableInstance.getHeaderGroups().map(headerGroup => (
        <tr key={headerGroup.id}>
          {headerGroup.headers.map(header => (
            <th key={header.id}>{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}</th>
          ))}
        </tr>
      ))}
    </thead>
    <tbody>
      {tableInstance.getRowModel().rows.map(row => (
        <tr key={row.id}>
          {row.getVisibleCells().map(cell => (
            <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
          ))}
        </tr>
      ))}
    </tbody>
  </table>
);
Renders the table component using the table instance. It includes headers and rows, iterating over each header group and row and using flexRender for rendering each cell.