Sau001
Sau001

Reputation: 1664

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

I am evaluating React-Material grid for my customer. One of the key feedback was the absence of alternate shading of rows, which impacts user experience.

https://material-ui.com/components/data-grid/#mit-version

Is this possible?

Actual

enter image description here

Desired

enter image description here

thank you,

Sau

Upvotes: 3

Views: 22617

Answers (4)

Zachary Haber
Zachary Haber

Reputation: 11027

MUI5 DataGrid Striping

For MUI5, as pointed out by keemor in the comments, you can use indexRelativeToCurrentPage parameter of the getRowClassName prop argument. For compatibility with the original undocumented Mui-even/Mui-odd class names, you can return those class names via this prop as below:

<DataGrid
  loading={loading}
  {...data}
  getRowClassName={(params) =>
    params.indexRelativeToCurrentPage % 2 === 0 ? 'Mui-even' : 'Mui-odd'
  }
/>

The indexRelativeToCurrentPage value does reset between pages, so the first item in page one will be even along with the first item in page 2, no matter how many items there are per page.

The :nth-child selectors mentioned in the MUI4 section is only a viable solution if you turn off data virtualization which is active by default. If you tried to use it with virtualization, then you'll end up with a strobe effect as you scroll due to the removal of elements outside the viewport.


MUI4 DataGrid Striping

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;
}

Upvotes: 16

Ken Lin
Ken Lin

Reputation: 1919

See the official StripedDataGrid component example.

Upvotes: 1

Hank
Hank

Reputation: 1291

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]
      },
    },
  }),
);

Upvotes: 2

Paito
Paito

Reputation: 1553

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)',
      },
    },
  }),
);

Upvotes: 3

Related Questions