Blog>
Snippets

Creating a Custom Cell Renderer in TanStack Table

Shows how to create and use a custom cell renderer in TanStack Table for customizing the display of data in a table cell.
import { useTable } from '@tanstack/react-table';
Import useTable hook from @tanstack/react-table to create and manage the table instance.
const data = React.useMemo(() => [{ colValue: 'example' }], []);
Define the data for the table using useMemo for performance optimization. This example uses a single row for simplicity.
const columns = React.useMemo(() => [
  {
    accessorKey: 'colValue', // accessor is the "key" in the data
    cell: (info) => <strong>{info.getValue()}</strong>,
  },
], []);
Define the columns for the table. The 'accessorKey' specifies the key to access the value from each row object. The 'cell' property is used to define a custom renderer, which in this case wraps the value in a <strong> tag.
const MyTable = () => {
  const {
    getTableProps,
    getTableBodyProps,
    rows,
    prepareRow,
  } = useTable({ columns, data });

  return (
    <table {...getTableProps()}>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.getVisibleCells().map(cell => (
                <td {...cell.getCellProps()}>{cell.renderCell()}</td>
              ))}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};
Defines the MyTable component which uses the useTable hook to create a table instance. It renders a table with a single row and a custom cell that renders the cell value inside a <strong> tag using the custom renderer defined in the columns.