How to make React-Material UI data grid to render rows using alternate shades?

Viewed 11598
4 Answers

It's pretty simple to add in via a CSS selector.

If you add a selector for the odd rows .Mui-odd, then you can set the color of the background and make it striped. You could use .Mui-even instead for the other half.

.MuiDataGrid-row.Mui-odd {
  background-color: aliceblue;
}

Here's a working codesandbox

If you wanted to use :nth-child, then you'd need :nth-child(even) for the same set of rows as .Mui-odd, though .Mui-odd keeps up it's ordering between pages, where the psuedo selector doesn't.

.MuiDataGrid-row:nth-child(even){
  background-color: aliceblue;
}

Using this solution you can make it dynamic with light/dark modes and also preserve mouse hover effects.

const useStyles = makeStyles((theme) =>
  ({
    root: {
      '& .MuiDataGrid-row.Mui-even:not(:hover)': {
        backgroundColor: theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.04)' : 'rgba(255, 255, 255, 0.04)',
      },
    },
  }),
);

This worked for me in MUI v5 - TypeScript.

const useStyles = makeStyles((theme: Theme) =>
  ({
    root: {
      '& .MuiDataGrid-row:nth-child(odd)': {
        backgroundColor: theme.palette.mode === 'light' ? theme.palette.secondary[300] : theme.palette.secondary[900]
      },
    },
  }),
);

See the official StripedDataGrid component example.

Related