I've been following https://blog.logrocket.com/complete-guide-building-smart-data-table-react/. To apply custom styling depending on cell value, I'm updating the column object like so:
return {
Header: key,
accessor: key,
width: "150",
sortType: "basic",
Cell: ({cell: {value} }) => {
if (value == "Error") {
return <RedCell/>
}
...
}
}
Is it possible instead to apply custom styling to the row containing the cell? I guess a prop would have to be passed down to row, but am just not clear at all on how to do this.
Any pointers would be much appreciated.
For anyone stumbling upon this issue, this has been answered by the author of the react-table
library here — https://spectrum.chat/react-table/general/v7-row-getrowprops-how-to-pass-custom-props-to-the-row~ff772376-0696-49d6-b259-36ef4e558821
In your Table component, you pass on any prop (say, rowProps
) of your choice for rows —
<Table
columns={columns}
data={data}
rowProps={row => ({
onClick: () => alert(JSON.stringify(row.values)),
style: {
cursor: "pointer"
}
})}
/>
Then to actually use this —
function Table({ columns, data, rowProps = () => ({}) }) {
// Use the state and functions returned from useTable to build your UI
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
columns,
data
});
// Render the UI for your table
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps(rowProps(row))}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
);
})}
</tr>
)
)}
</tbody>
</table>
);
}