Blog>
Snippets

Initializing React TanStack Table with Facets

Show how to set up a basic React TanStack Table and configure it to support faceted search, using dummy data for demonstration.
import { useTable } from '@tanstack/react-table';
import React, { useMemo, useState } from 'react';
Import necessary hooks from React TanStack Table and React.
const data = useMemo(() => [
  { 'name': 'Project A', 'status': 'In Progress', 'category': 'Development' },
  { 'name': 'Project B', 'status': 'Completed', 'category': 'Design' },
  // Add more data as needed
], []);
Define dummy dataset to simulate fetched data.
const columns = useMemo(() => [
  { accessorFn: row => row.name, id: 'name', header: 'Project Name' },
  { accessorFn: row => row.status, id: 'status', header: 'Status' },
  { accessorFn: row => row.category, id: 'category', header: 'Category' },
], []);
Define table columns mapping to the data fields.
const [filters, setFilters] = useState({});

const filterData = (row, filters) => {
  return Object.entries(filters).every(([key, value]) => {
    return String(row[key]).includes(value);
  });
};
Set up state for filters and a function to filter data based on these filters.
const filteredData = useMemo(() => {
  return data.filter(row => filterData(row, filters));
}, [data, filters]);
Compute filtered data based on the current filters applied.
const tableInstance = useTable({
  data: filteredData,
  columns,
});
const { getTableProps, getTableBodyProps, rows, prepareRow } = tableInstance;
Initialize the table with filtered data and unpack necessary properties and methods from the table instance.
// Example of rendering the table in return statement of the component
return (
  <table {...getTableProps()}>
    <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>
);
Basic rendering of the table with simplicity in mind, focusing on the structure rather than styling.