how to change the color of childs elements on card hover in material ui?

Viewed 729
2 Answers

To change a style of a child when hovering over a parent using React Material UI styles, we can call makeStyles with the &:hover selector of the parent element to change the styles when we hover over the child element.

for example :- here outerdiv is perent element and addIcon is child element

import * as React from "react";
import { Grid, makeStyles } from "@material-ui/core";
import AddIcon from "@material-ui/icons/Add";

const useStyles = makeStyles((theme) => ({
  outerDiv: {
    backgroundColor: theme.palette.grey[200],
    padding: theme.spacing(4),
    "&:hover": {
      cursor: "pointer",
      backgroundColor: theme.palette.grey[100],
      "& $addIcon": {
        color: "purple"
      }
    }
  },
  addIcon: () => ({
    height: 50,
    width: 50,
    color: theme.palette.grey[400],
    marginBottom: theme.spacing(2)
  })
}));

export default function App() {
  const classes = useStyles();

  return (
    <Grid container>
      <Grid item className={classes.outerDiv}>
        <AddIcon className={classes.addIcon} />
      </Grid>
    </Grid>
  );
}

because you set color in attribute, and if u set color in color attribute, your hover not working.

    <Typography
      variant="body2"
      color={theme.palette.primary.dark}
    </Typography>

if you want set hover for this, you have to set default color and hover in makeStyles() or styled().

like this one, i make for myself:

import { styled } from '@mui/material/styles';
import MuiListItemButton from '@mui/material/ListItemButton';

const ListItemButton = styled(MuiListItemButton)(({ theme }) => ({
  color: theme.palette.primary.main,
  '& svg': { color: theme.palette.primary.main },
  '&:hover, &:focus': {
    color: theme.palette.white.main,
    backgroundColor: theme.palette.primary.main,
    '& svg': { color: theme.palette.white.main },
  },
}));
Related