Search code examples
reactjsmaterial-uidatagrid

How can I highlight rows in a MUI data grid based on a specific value in a column?


I want to change the color of specific rows in my data grid. The way the color of the row should be determined is if a certain value is present in the 'Admin' column of the row.

The 'Admin' column contains a string of two words, a first name and a last name. Like "John Bob" or "Mike Martin".

When an Admin logs in to the app, rows with his name in it should be highlighted in yellow.

The Admin's name is also currently stored in sessionStorage. So to get the admin name I need to do sessionStorage.getItem("username"). This returns a value like "John Bob".

Im currently using the prop

getRowClassName={(params) => `color--${params.row.admin}`}

to create classnames.

I also have some custom styling for my data grid in an sx. It looks like

sx={{

`"& .color--John.Bob": {
  backgroundColor: "yellow",
  },`

}}

This currently works if John Bob logs in to the app. But I need it to work for all admins who log onto the app.

Ideally the code would look something like

sx={{

`"& .color--Firstname.Lastname": {
  backgroundColor: "yellow",
  },`

}}

Solution

  • you can think of it in another way instead of adding the first name and last name in the class, you can just add a simple check to check if this value equals the value stored in the session storage, then you can give it some active or me class name:

    const loggedInUserName = sessionStorage.getItem("username");
    getRowClassName={(params) => params.row.admin === loaggedInUserName ? 'me' : null }}
    
    

    and then in the class of me you can the styles you want