Blog>
Snippets

Setting Up TanStack Table in a React Project

Demonstrate the steps to install TanStack Table v8, import the necessary modules, and create a basic table component with static data in a React application.
// Step 1: Install TanStack Table v8
// Run this command in your terminal
npm install @tanstack/react-table
This command installs the TanStack Table package required for creating tables in a React application.
import React from 'react';
import { useReactTable, createColumnHelper } from '@tanstack/react-table';
Import React and the necessary hooks from the TanStack Table package.
// Define your data structure
const defaultData = [
  { id: 1, firstName: 'Jane', lastName: 'Doe' },
  { id: 2, firstName: 'John', lastName: 'Doe' }
];
Define a simple data structure to populate the table.
const columnHelper = createColumnHelper();
const columns = [
  columnHelper.accessor('id', {
    header: 'ID'
  }),
  columnHelper.accessor('firstName', {
    header: 'First Name'
  }),
  columnHelper.accessor('lastName', {
    header: 'Last Name'
  })
];
Utilize the createColumnHelper function to define columns for your table based on data keys.
function Table() {
  const table = useReactTable({
    columns,
    data: defaultData,
    getCoreRowModel: getCoreRowModel()
  });
  
  return (
    <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>
  );
}
Create a React function component that renders a table using the TanStack Table. This demonstrates using hooks to manage table state and render.