How to change the hover color of Material-UI table?

Viewed 39037

I am using React and Material UI for my web application. I want to change the hover color of table row but cannot do that.

Sample code:

x={
  hover:{
    color:'green'
  }
}

<TableRow
  hover
  key={lead.id} className={classes.row}
  classes={{
    hover:x.hover
  }}
  onClick={() => {}}
>
8 Answers

I've got this solution so far. Maybe there are other approaches to override css of tableRow but this one works like a charm:

const styles = theme => ({
tableRow: {
    "&:hover": {
      backgroundColor: "blue !important"
    }
  }
});


<TableRow hover
      key={lead.id} className={classes.tableRow}

      onClick={() => {}}>

Feel free to ask any question.

tableRow: {
    hover: {
        "&$hover:hover": {
            backgroundColor: '#49bb7b',
        },
    },
}

<TableRow className={classes.tableRow} key={n.id} hover onClick={event => this.handleClick(event)}>Text</TableRow>

The implementation of the TableRow component and the customizing components page show that you need to override two classes, root.hover:hover and .hover to change the hover color.

const useStyles = makeStyles((theme) => ({
  /* Styles applied to the root element. */
  root: {
    // Default root styles
    color: 'inherit',
    display: 'table-row',
    verticalAlign: 'middle',
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,

    '&$hover:hover': {
      // Set hover color
      backgroundColor: theme.palette.action.hover,
    },
  },

  /* Pseudo-class applied to the root element if `hover={true}`. */
  hover: {},
}));

Then in your component, you can apply the styles to the classes prop.

const HelloWorld = () => {
  const classes = useStyles();
  return (
    <TableRow classes={classes}><TableCell></TableCell></TableRow>
  );
};

You can maintain dependency on the Material UI hover prop by using

hover: {
  '&:hover': {
    backgroundColor: 'green !important',
  },
},

just put hover in the TableRow, but not the header Tablerow

 <StyledTableRow hover key={row.name}>

@material-ui/core/TableRow has built in code to deal with hover, it worked for me.

This is a trivial task in MUI v5. See the docs here:

<Table
  sx={{
    "& .MuiTableRow-root:hover": {
      backgroundColor: "primary.light"
    }
  }}
>

Live Demo

Codesandbox Demo

Just in case, if you are using the component overrides and want to do a style override you have to target the root and not the hover rule. I spent quite a while trying to get the pseudo :hover to work on that but it wouldn't ever work.

Here's what I have.

MuiTableRow: {
    styleOverrides: {
        // Even though there is a hover rule we have to override it here. Don't ask.
        root: {
            '&.MuiTableRow-hover:hover': {
                backgroundColor: 'blue',
            },
        },
    },
},

Use this is you want to override the component at the theme level vs styled overrides, sx or useStyles.

Related