Custom Cell Renderer with React TanStack Table
Demonstrate creating a custom cell renderer in React TanStack Table for a more personalized column display.
import { useTable } from '@tanstack/react-table';
import React from 'react';
First, we import necessary hooks from '@tanstack/react-table' and React.
const CustomCell = ({ value }) => (
<div style={{ color: 'blue' }}>{value}</div>
);
Defines a custom cell rendering component, `CustomCell`, which will display its content in blue.
const data = React.useMemo(
() => [
{ id: 1, firstName: 'John', lastName: 'Doe' },
{ id: 2, firstName: 'Jane', lastName: 'Doe' }
],
[]
);
Sets up the data to be displayed in the table. Here we have an array of objects with `id`, `firstName`, and `lastName` properties.
const columns = React.useMemo(
() => [
{
accessorKey: 'firstName',
header: 'First Name',
cell: info => <CustomCell value={info.getValue()} />
},
{
accessorKey: 'lastName',
header: 'Last Name',
// Uses the default rendering
}
],
[]
);
Creates column definitions. The `firstName` column uses the custom renderer `CustomCell`.
function Table() {
const {
getTableProps,
getTableBodyProps,
headers,
rows,
prepareRow,
} = useTable({
data,
columns,
});
return (
<table {...getTableProps()}>
<thead>
{headers.map(header => (
<th {...header.getHeaderProps()}>{header.render('Header')}</th>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
))}
</tr>
);
})}
</tbody>
</table>
);
}
The main `Table` component uses the `useTable` hook from TanStack Table to construct and manage the table given the data and columns. This component renders an HTML table with custom styling applied to the `firstName` cells.