Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override style of nested Material UI component from the ancestors?

I am using a component from an external library that does not allow me to change much of its style, but I would like to change the style of a button that is a material ui button, when inspecting the element it clearly shows the classes MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit

how can I override the MuiIconButton-root style, for instance? this is my component:

class MyComponent extends Component {

    render() {
        const { classes } = this.props;
        return (
            <div className={classes.myComponent}>
                <3rdPartyComponent />
            </div>
        );

    }
}


export default withStyles(styles)(MyComponent)

I have tried declaring my styles function as follows, without success:

const styles = theme => ({
  myComponent: {
    "&.MuiIconButton-root": {
      padding: "0px"
    }
  }
});

Can anybody help me? Thanks in advance.

like image 677
Akira Kotsugai Avatar asked Mar 03 '20 10:03

Akira Kotsugai


1 Answers

Let's say that the class name generated for myComponent is myComponent-jss123. The selector you used in your styles (&.MuiIconButton-root) would be equivalent to .myComponent-jss123.MuiIconButton-root which would match any element that has both of these classes applied to it. I believe your intent was to match icon buttons which are descendants of the div on which you are applying the myComponent class. In this case you need to use the descendant combinator represented by a space, so the appropriate styles would look like the following:

const styles = theme => ({
  myComponent: {
    "& .MuiIconButton-root": {
      padding: 0
    }
  }
});

Here's a full working example:

import React from "react";
import IconButton from "@material-ui/core/IconButton";
import DeleteIcon from "@material-ui/icons/Delete";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  myComponent: {
    "& .MuiIconButton-root": {
      padding: 0
    }
  }
});
const ThirdPartyComponent = () => {
  return (
    <div>
      I'm a third party component that contains an IconButton:
      <IconButton color="primary">
        <DeleteIcon />
      </IconButton>
    </div>
  );
};
export default function App() {
  const classes = useStyles();
  return (
    <div className={classes.myComponent}>
      <ThirdPartyComponent />
    </div>
  );
}

Edit target descendant icon button

Related documentation:

  • https://cssinjs.org/jss-plugin-nested/?v=v10.0.4#use--to-reference-selector-of-the-parent-rule
  • https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors
  • https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator
like image 142
Ryan Cogswell Avatar answered Nov 12 '22 15:11

Ryan Cogswell