5
votes

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.

1
Material-UI styles document:material-ui.com/styles/basicskeikai
@keikai I have already gone through that documentation and could not find how to override "grandchildren"Akira Kotsugai

1 Answers

12
votes

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: