T
TanStack3y ago
absent-sapphire

React table value-based styling

I may be confused but it seems to me that in the former react-table v7 version, we used to have more control on the way the rows would be rendered. In the attached screenshot (codesandbox https://codesandbox.io/s/ancient-frog-rsx361), I'd rather have the styling set at the <td/> level, not its child (so that padding would look cleaner). What's the right approach for this with v8 ? Old version (<td/> would get its own cell-value-based styling getColumnProps + getCellProps)
<tbody {...getTableBodyProps()}>
{page.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps(getRowProps(row))}>
{row.cells.map((cell) => (
<td
{...cell.getCellProps([
{
className: cell.column.className,
style: cell.column.style,
},
getColumnProps(cell.column),
getCellProps(cell),
])}
>
{cell.render("Cell")}
</td>
))}
</tr>
);
})}
</tbody>
<tbody {...getTableBodyProps()}>
{page.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps(getRowProps(row))}>
{row.cells.map((cell) => (
<td
{...cell.getCellProps([
{
className: cell.column.className,
style: cell.column.style,
},
getColumnProps(cell.column),
getCellProps(cell),
])}
>
{cell.render("Cell")}
</td>
))}
</tr>
);
})}
</tbody>
New v8 version (<td/> styling no longer affected by cell value)
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
Thanks
No description
2 Replies
wise-white
wise-white3y ago
For me, I would set columnDef.meta.td.className and columnDef.meta.td.style so that I can:
<td
key={cell.id}
className={cx(myTableClassName, cell.column.columnDef.meta.td.className)}
{...(cell.column.columnDef.meta?.td?.style ? { style: cell.column.columnDef.meta?.td?.style } : null )}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
<td
key={cell.id}
className={cx(myTableClassName, cell.column.columnDef.meta.td.className)}
{...(cell.column.columnDef.meta?.td?.style ? { style: cell.column.columnDef.meta?.td?.style } : null )}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
Also use declaration merging for better TypeScript experience: https://tanstack.com/table/v8/docs/api/core/column-def#meta
ColumnDef | TanStack Table Docs
Column definitions are plain objects with the following options: Options
absent-sapphire
absent-sapphireOP3y ago
I've played with your solution, it seems flexible enough for my use case. The docs for TS declaration merging were useful. Thanks @Z. Aru

Did you find this page helpful?