George Mauer
George Mauer

Reputation: 122222

How to reference another style class for complex selectors with material-ui

With something like styled-components you were able to reference the generated classes of other components like so:

const Header = styled.header`
  font-weight: bold;
  display: flex;
`

const CloseButton = styled.button`
   padding: 0;
   border-width: 0;

   &:before {
     content: "x";
   }

   ${Header} > & {
     margin-left: auto;
   }
`

Material-UI has both the styled function that is patterned on this and the makeStyles function (which is in some ways superior), yet I cannot figure out how to achieve a similar effect here and to combine class selectors in more complex ways. The documentation is very sparse on the topic, they just say that you can used styled as a mostly drop in replacement but then the actual api for it is with an object where this sort of thing is not possible.

So how do you do more complex selectors?

Upvotes: 5

Views: 3884

Answers (1)

95faf8e76605e973
95faf8e76605e973

Reputation: 14201

MUI uses CSS-in-JS

Use $ruleName to reference a local rule name within the same makeStyles style sheet.

const useStyles = makeStyles({
  Header: {
    fontWeight: "bold",
    display: "flex"
  },
  CloseButton: {
    padding: 0,
    borderWidth: 0,

    "&:before": {
      content: "'x'"
    },

    "$Header > &": { // <-- pay attention to usage of $
      marginLeft: "auto"
    }
  }
});

Below is what your CSS would look like:

enter image description here

Upvotes: 11

Related Questions