Blog>
Snippets

Custom Cell Rendering

Explores custom cell rendering in React TanStack Table by defining a template for cells that includes conditional formatting based on the cell's value.
import { useReactTable } from '@tanstack/react-table';

// Define columns with custom cell rendering
const columns = [
  {
    accessorKey: 'status', // Accessor matches the data key
    header: 'Status',
    cell: info => {
      // Conditional rendering based on the cell value
      if(info.getValue() === 'Active') {
        return <span style={{ color: 'green' }}>Active</span>;
      } else if(info.getValue() === 'Inactive') {
        return <span style={{ color: 'red' }}>Inactive</span>;
      }
      // Default rendering
      return info.renderValue();
    },
  },
  // Other columns...
];
This code snippet defines a column for a table where cells within the 'status' column are rendered differently based on their value. If the status is 'Active', the cell content appears in green. If the status is 'Inactive', it appears in red. This is achieved using a custom cell renderer function defined in the 'cell' property of the column object.
const data = [
  { status: 'Active', /* Other data fields */ },
  { status: 'Inactive', /* Other data fields */ },
  // More rows...
];
This array represents the data being rendered in the table. Each object in the array corresponds to a row, with keys matching the 'accessorKey' defined in our columns configuration.
function DataTable() {
  const { getTableProps, getTableBodyProps, headers, rows, prepareRow } = useReactTable({
    data,
    columns,
  });

  // Render table with custom cell rendering
  return (
    <table {...getTableProps()}>
      <thead>
        <tr>{headers.map(header => <th {...header.getHeaderProps()}>{header.render('Header')}</th>)}</tr>
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.getVisibleCells().map(cell => <td {...cell.getCellProps()}>{cell.render('Cell')}</td>)}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
This function component creates a table using the defined columns and data. It utilizes the 'useReactTable' hook from '@tanstack/react-table' to manage table state and rendering logic. The component renders the table's header and body by mapping through the 'headers' and 'rows', calling the custom cell renderer for the 'status' column as defined.