Categories
React Answers

How to change a style of a child when hovering over a parent using React Material UI styles?

Spread the love

Sometimes, we want to change a style of a child when hovering over a parent using React Material UI styles.

In this article, we’ll look at how to change a style of a child when hovering over a parent using React Material UI styles.

How to change a style of a child when hovering over a parent using React Material UI styles?

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 instance, we write:

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

We call makeStyles with a function that has the outerDiv class property with the "&:hover" property inside it.

We set "&:hover" to a function that changes the background color of the child element.

Also, we have the "& $addIcon" property to set the color of the child element.

Next, we apply the outerDiv class by setting the className prop of Grid to classes.outerDiv.

As a result, when we hover over the Grid, we see that the add icon is purple.

Conclusion

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *