Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
George Mauer Avatar asked Dec 30 '22 20:12

George Mauer


1 Answers

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

like image 153
95faf8e76605e973 Avatar answered Jan 05 '23 15:01

95faf8e76605e973