📄 tanstack/table/v8/docs/framework/react/examples/sub-components

File: sub-components.md | Updated: 11/15/2025

Source: https://tanstack.com/table/v8/docs/framework/react/examples/sub-components



TanStack

Table v8v8

Search...

+ K

Auto

Log In

TanStack StartRC

Docs Examples GitHub Contributors

TanStack Router

Docs Examples GitHub Contributors

TanStack Query

Docs Examples GitHub Contributors

TanStack Table

Docs Examples Github Contributors

TanStack Formnew

Docs Examples Github Contributors

TanStack DBbeta

Docs Github Contributors

TanStack Virtual

Docs Examples Github Contributors

TanStack Paceralpha

Docs Examples Github Contributors

TanStack Storealpha

Docs Examples Github Contributors

TanStack Devtoolsalpha

Docs Github Contributors

More Libraries

Maintainers Partners Support Learn StatsBETA Discord Merch Blog GitHub Ethos Brand Guide

Documentation

Framework

React logo

React

Version

v8

Search...

+ K

Menu

Getting Started

Core Guides

Feature Guides

Core APIs

Feature APIs

Enterprise

Examples

Framework

React logo

React

Version

v8

Menu

Getting Started

Core Guides

Feature Guides

Core APIs

Feature APIs

Enterprise

Examples

React Example: Sub Components

Github StackBlitz CodeSandbox

===============================================================================================================================================================================================================================================================================================================================================================================================================================

Code ExplorerCode

Interactive SandboxSandbox

  • src

    • index.css file iconindex.css

    • main.tsx file iconmain.tsx

    • makeData.ts file iconmakeData.ts

  • .gitignore file icon.gitignore

  • README.md file iconREADME.md

  • index.html file iconindex.html

  • package.json file iconpackage.json

  • tsconfig.json file icontsconfig.json

  • vite.config.js file iconvite.config.js

tsx

import React, { Fragment } from 'react'
import ReactDOM from 'react-dom/client'

import './index.css'

import {
  useReactTable,
  getCoreRowModel,
  getExpandedRowModel,
  ColumnDef,
  flexRender,
  Row,
} from '@tanstack/react-table'
import { makeData, Person } from './makeData'

const columns: ColumnDef<Person>[] = [\
  {\
    header: 'Name',\
    footer: props => props.column.id,\
    columns: [\
      {\
        id: 'expander',\
        header: () => null,\
        cell: ({ row }) => {\
          return row.getCanExpand() ? (\
            <button\
              {...{\
                onClick: row.getToggleExpandedHandler(),\
                style: { cursor: 'pointer' },\
              }}\
            >\
              {row.getIsExpanded() ? '👇' : '👉'}\
            </button>\
          ) : (\
            '🔵'\
          )\
        },\
      },\
      {\
        accessorKey: 'firstName',\
        header: 'First Name',\
        cell: ({ row, getValue }) => (\
          <div\
            style={{\
              // Since rows are flattened by default,\
              // we can use the row.depth property\
              // and paddingLeft to visually indicate the depth\
              // of the row\
              paddingLeft: `${row.depth * 2}rem`,\
            }}\
          >\
            {getValue<string>()}\
          </div>\
        ),\
        footer: props => props.column.id,\
      },\
      {\
        accessorFn: row => row.lastName,\
        id: 'lastName',\
        cell: info => info.getValue(),\
        header: () => <span>Last Name</span>,\
        footer: props => props.column.id,\
      },\
    ],\
  },\
  {\
    header: 'Info',\
    footer: props => props.column.id,\
    columns: [\
      {\
        accessorKey: 'age',\
        header: () => 'Age',\
        footer: props => props.column.id,\
      },\
      {\
        header: 'More Info',\
        columns: [\
          {\
            accessorKey: 'visits',\
            header: () => <span>Visits</span>,\
            footer: props => props.column.id,\
          },\
          {\
            accessorKey: 'status',\
            header: 'Status',\
            footer: props => props.column.id,\
          },\
          {\
            accessorKey: 'progress',\
            header: 'Profile Progress',\
            footer: props => props.column.id,\
          },\
        ],\
      },\
    ],\
  },\
]

type TableProps<TData> = {
  data: TData[]
  columns: ColumnDef<TData>[]
  renderSubComponent: (props: { row: Row<TData> }) => React.ReactElement
  getRowCanExpand: (row: Row<TData>) => boolean
}

function Table({
  data,
  columns,
  renderSubComponent,
  getRowCanExpand,
}: TableProps<Person>): JSX.Element {
  const table = useReactTable<Person>({
    data,
    columns,
    getRowCanExpand,
    getCoreRowModel: getCoreRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
  })

  return (
    <div className="p-2">
      <div className="h-2" />
      <table>
        <thead>
          {table.getHeaderGroups().map(headerGroup => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map(header => {
                return (
                  <th key={header.id} colSpan={header.colSpan}>
                    {header.isPlaceholder ? null : (
                      <div>
                        {flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                      </div>
                    )}
                  </th>
                )
              })}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map(row => {
            return (
              <Fragment key={row.id}>
                <tr>
                  {/* first row is a normal row */}
                  {row.getVisibleCells().map(cell => {
                    return (
                      <td key={cell.id}>
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </td>
                    )
                  })}
                </tr>
                {row.getIsExpanded() && (
                  <tr>
                    {/* 2nd row is a custom 1 cell row */}
                    <td colSpan={row.getVisibleCells().length}>
                      {renderSubComponent({ row })}
                    </td>
                  </tr>
                )}
              </Fragment>
            )
          })}
        </tbody>
      </table>
      <div className="h-2" />
      <div>{table.getRowModel().rows.length} Rows</div>
    </div>
  )
}

const renderSubComponent = ({ row }: { row: Row<Person> }) => {
  return (
    <pre style={{ fontSize: '10px' }}>
      <code>{JSON.stringify(row.original, null, 2)}</code>
    </pre>
  )
}

function App() {
  const [data] = React.useState(() => makeData(10))

  return (
    <Table
      data={data}
      columns={columns}
      getRowCanExpand={() => true}
      renderSubComponent={renderSubComponent}
    />
  )
}

const rootElement = document.getElementById('root')
if (!rootElement) throw new Error('Failed to find the root element')

ReactDOM.createRoot(rootElement).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)


import React, { Fragment } from 'react'
import ReactDOM from 'react-dom/client'

import './index.css'

import {
  useReactTable,
  getCoreRowModel,
  getExpandedRowModel,
  ColumnDef,
  flexRender,
  Row,
} from '@tanstack/react-table'
import { makeData, Person } from './makeData'

const columns: ColumnDef<Person>[] = [\
  {\
    header: 'Name',\
    footer: props => props.column.id,\
    columns: [\
      {\
        id: 'expander',\
        header: () => null,\
        cell: ({ row }) => {\
          return row.getCanExpand() ? (\
            <button\
              {...{\
                onClick: row.getToggleExpandedHandler(),\
                style: { cursor: 'pointer' },\
              }}\
            >\
              {row.getIsExpanded() ? '👇' : '👉'}\
            </button>\
          ) : (\
            '🔵'\
          )\
        },\
      },\
      {\
        accessorKey: 'firstName',\
        header: 'First Name',\
        cell: ({ row, getValue }) => (\
          <div\
            style={{\
              // Since rows are flattened by default,\
              // we can use the row.depth property\
              // and paddingLeft to visually indicate the depth\
              // of the row\
              paddingLeft: `${row.depth * 2}rem`,\
            }}\
          >\
            {getValue<string>()}\
          </div>\
        ),\
        footer: props => props.column.id,\
      },\
      {\
        accessorFn: row => row.lastName,\
        id: 'lastName',\
        cell: info => info.getValue(),\
        header: () => <span>Last Name</span>,\
        footer: props => props.column.id,\
      },\
    ],\
  },\
  {\
    header: 'Info',\
    footer: props => props.column.id,\
    columns: [\
      {\
        accessorKey: 'age',\
        header: () => 'Age',\
        footer: props => props.column.id,\
      },\
      {\
        header: 'More Info',\
        columns: [\
          {\
            accessorKey: 'visits',\
            header: () => <span>Visits</span>,\
            footer: props => props.column.id,\
          },\
          {\
            accessorKey: 'status',\
            header: 'Status',\
            footer: props => props.column.id,\
          },\
          {\
            accessorKey: 'progress',\
            header: 'Profile Progress',\
            footer: props => props.column.id,\
          },\
        ],\
      },\
    ],\
  },\
]

type TableProps<TData> = {
  data: TData[]
  columns: ColumnDef<TData>[]
  renderSubComponent: (props: { row: Row<TData> }) => React.ReactElement
  getRowCanExpand: (row: Row<TData>) => boolean
}

function Table({
  data,
  columns,
  renderSubComponent,
  getRowCanExpand,
}: TableProps<Person>): JSX.Element {
  const table = useReactTable<Person>({
    data,
    columns,
    getRowCanExpand,
    getCoreRowModel: getCoreRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
  })

  return (
    <div className="p-2">
      <div className="h-2" />
      <table>
        <thead>
          {table.getHeaderGroups().map(headerGroup => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map(header => {
                return (
                  <th key={header.id} colSpan={header.colSpan}>
                    {header.isPlaceholder ? null : (
                      <div>
                        {flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                      </div>
                    )}
                  </th>
                )
              })}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map(row => {
            return (
              <Fragment key={row.id}>
                <tr>
                  {/* first row is a normal row */}
                  {row.getVisibleCells().map(cell => {
                    return (
                      <td key={cell.id}>
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </td>
                    )
                  })}
                </tr>
                {row.getIsExpanded() && (
                  <tr>
                    {/* 2nd row is a custom 1 cell row */}
                    <td colSpan={row.getVisibleCells().length}>
                      {renderSubComponent({ row })}
                    </td>
                  </tr>
                )}
              </Fragment>
            )
          })}
        </tbody>
      </table>
      <div className="h-2" />
      <div>{table.getRowModel().rows.length} Rows</div>
    </div>
  )
}

const renderSubComponent = ({ row }: { row: Row<Person> }) => {
  return (
    <pre style={{ fontSize: '10px' }}>
      <code>{JSON.stringify(row.original, null, 2)}</code>
    </pre>
  )
}

function App() {
  const [data] = React.useState(() => makeData(10))

  return (
    <Table
      data={data}
      columns={columns}
      getRowCanExpand={() => true}
      renderSubComponent={renderSubComponent}
    />
  )
}

const rootElement = document.getElementById('root')
if (!rootElement) throw new Error('Failed to find the root element')

ReactDOM.createRoot(rootElement).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)

Expanding

Fully Controlled

Partners Become a Partner

Code RabbitCode Rabbit CloudflareCloudflare AG GridAG Grid NetlifyNetlify NeonNeon WorkOSWorkOS ClerkClerk ConvexConvex ElectricElectric SentrySentry PrismaPrisma StrapiStrapi UnkeyUnkey

scarf analytics