Blog>
Snippets

Defining a Sub Component in React TanStack Table

This example demonstrates how to define a sub component for a specific row in React TanStack Table to display more detailed information about an item when the row is expanded.
import { useExpanded, useTable } from '@tanstack/react-table';
First, import the necessary hooks from '@tanstack/react-table' to manage table state and row expansion.
const table = useTable(
  {
    columns,
    data,
    getSubRows: (row) => row.subRows,
  },
  useExpanded // Use the useExpanded plugin hook
);
Initialize the table instance with 'useTable' and configure it to handle sub-rows by specifying the 'getSubRows' option. Additionally, use the 'useExpanded' plugin to enable row expansion functionality.
// Custom toggle component
const SubRowToggle = ({ row }) => (
  <span
    {...row.getToggleRowExpandedProps()}
  >
    {row.isExpanded ? '-' : '+'}
  </span>
);
Define a 'SubRowToggle' component that uses 'row.getToggleRowExpandedProps()' to manage the expanded state. It displays '+' or '-' based on whether the row is expanded.
{table.getRowModel().rows.map(row => (
  <React.Fragment key={row.id}>
    <tr>
      <td>
        <SubRowToggle row={row} />
      </td>
      {row.getVisibleCells().map(cell => (
        <td key={cell.id}>{cell.renderCell()}</td>
      ))}
    </tr>
    {row.isExpanded ? (
      <tr>
        <td colSpan={row.cells.length}>SubComponent Content Here</td>
      </tr>
    ) : null}
  </React.Fragment>
))}
Render each row with the 'SubRowToggle' component. When a row is expanded, a new table row is added below it to display more detailed information or sub-components.