Reputation: 297
I have a basic Material UI v4 datagrid. I am trying to change the any row that has age
of 16 to all grey color: 'grey'
. I am struggling to do this. The docs are not very clear on how to change an entire rows font color. Here is the code.
import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";
const columns = [
{ field: "id", headerName: "ID", width: 70 },
{ field: "firstName", headerName: "First name", width: 130 },
{ field: "lastName", headerName: "Last name", width: 130 },
{
field: "age",
headerName: "Age",
type: "number",
width: 90
},
{
field: "fullName",
headerName: "Full name",
description: "This column has a value getter and is not sortable.",
sortable: false,
width: 160,
valueGetter: (params) =>
`${params.getValue("firstName") || ""} ${
params.getValue("lastName") || ""
}`
}
];
const rows = [
{ id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
{ id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
{ id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
{ id: 4, lastName: "Stark", firstName: "Arya", age: 16 }
];
export default function App() {
const [selectionModel, setSelectionModel] = React.useState([]);
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={25}
checkboxSelection
hideFooterPagination
onSelectionModelChange={(newSelection) => {
setSelectionModel(newSelection.selectionModel);
}}
selectionModel={selectionModel}
/>
{selectionModel.map(val =><h1>{val}</h1>)}
</div>
);
}
I'm trying to do something like this (of course this doesn't work)
const greyOut = () => {
const data = row.age
if (data == 16){
return (
<TableRow style={{ color: 'grey'}}>{row}</TableRow>
)}
}
Can anyone help with this?
Upvotes: 4
Views: 4294
Reputation: 3480
You can make use of getRowClassName
prop in <DataGrid/>
. This way you can apply certain css classes to all rows matching the condition.
params.row
lets you access all values inside a row.
<DataGrid
...
getRowClassName={(params) => {
return params.row.age === 16 ? "highlight" : "";
}}
...
/>
Now you can either use a classical css stylesheet or add an additional sx
prop to your <DataGrid/>
:
<DataGrid
...
sx={{
".highlight": {
bgcolor: "grey",
"&:hover": {
bgcolor: "darkgrey",
},
},
}}
/>
Upvotes: 8