Blog>
Snippets

Implementing a basic React TanStack Table with Column Filtering

Demonstrate how to set up a React TanStack Table component with basic column filtering functionality, including defining columns and applying a default filter.
import { useTable } from '@tanstack/react-table';
import React from 'react';
Import the necessary React and TanStack Table hooks to get started.
const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({
    columns,
    data,
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};
Define a Table component that takes in columns and data props for dynamic table creation. Utilize getTableProps and getTableBodyProps for proper rendering and handling of the table and its body respectively.
const columns = React.useMemo(
  () => [
    {
      Header: 'ID',
      accessor: 'id',
    },
    {
      Header: 'Name',
      accessor: 'name',
    },
    {
      Header: 'Email',
      accessor: 'email',
    }
  ],
  [],
);
Define column configurations using React.useMemo for optimized rendering. Each column is defined with a Header and an accessor which points to the key in the data.
const App = () => {
  const data = React.useMemo(
    () => [
      { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
      { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' }
    ],
    [],
  );

  return <Table columns={columns} data={data} />;
};
Define the App component that provides columns and data to the Table component. Here, useMemo is used to memorize the data and avoid recalculations on every render.
export default App;
Make the App component the default export of the module for use in other parts of the application.