top of page

How to implement Material UI Data Grid in your Project — Part-IV

[Customizing rows]

When it comes to row customization, there are mainly two things — Row height and Row styling

When it comes to rows, we often give props directly to DataGrid Component itself.By default, rowHeight would be 52px and headerHeight would be 56px.But why these arbitrary pixels? Because it matches material design guidelines.



import * as React from "react";
import { DataGrid } from "@mui/x-data-grid";
import { IconButton, Typography } from "@material-ui/core";
import PersonIcon from "@material-ui/icons/Person";const columns = [
{
field: "name",
width: 150,
type: "date",
renderHeader: (params) => {
return (
<Typography variant="h6">
Name
<IconButton>
{" "}
<PersonIcon />{" "}
</IconButton>
</Typography>
);
}
}
];const rows = [
{
id: 1,
name: "Messi"
},
{
id: 2,
name: "Ronaldo"
},
{
id: 3,
name: "Neymar"
}
];export default function RenderHeaderGrid() {
return (
<div style={{ height: 300, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
rowHeight={20}
headerHeight={40}
/>
</div>
);
}


When it comes to DataGrid styling, we need to first understand DOM structure and their default classes in DataGrid.


From MuiDataGrid-root we have basically two nodes — One for the Column header and the other for rows

Now we are going to use magic prop called getRowClassName which accepts rowparams as parameter return a class name.This class name will be added to div with class name of MuiDataGrid-row

import * as React from "react";import { DataGrid } from "@mui/x-data-grid";
import { useDemoData } from "@mui/x-data-grid-generator";
import { makeStyles } from "@mui/styles";const useStyles = makeStyles({
root: {
"& .styledrows": {
backgroundColor: "green"
}
}
});export default function StylingRowsGrid() {const classes = useStyles();
const { data } = useDemoData({
dataSet: "Commodity",
rowLength: 100
});return (<div style={{ height: 400, width: "100%" }} 
className={classes.root}>
<DataGrid 
{...data} 
getRowClassName={(params) => `styledrows`} />
</div>);
}
Basically, styling rows involves two steps — Declaring parent class for data grid parent
<div style={{ height: 400, width:100%}} className={classes.root}>

We need to give nested class inside parent class and the corresponding class name should be as same as getRowClassName prop’s return value

const useStyles = makeStyles({
root: {
"& .styledrows": {
backgroundColor: "green"
}
}
});

It's like saying whenever you see class ‘styledrows’ inside ‘root’ class, apply the mentioned styles.

So we need to add this nested class to every Datagrid row.That’s why we use getRowClassName.

<DataGrid 
{...data} 
getRowClassName={(params) => `styledrows`} />

The process above is actually a reverse of what we do normally in CSS. I hope it helps you a lot.

bottom of page