Target CSS child selector created by in material ui

Viewed 3100

I have styles like this:

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red'
  },
  active: {
    // here I want to target the 'container' className I created above like
    '& .container': {
      backgroundColor: 'green'
    }
  }
});

I want to target the container className I created inside of the active className. The above won't work because in the DOM, MUI will generate a unique name so I won't be targeting the right class. Wasn't able to find any SO answer or blog or documentation addressing this.

3 Answers

You can refer using $

You will have to modify your DOM little bit such that the active className is not the parent of container. Instead add the active className to the conatiner element itself.

so your css style might look like below

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red',
    
    '&$active': {
      backgroundColor: 'green'
    }
  },
  
});

$ rulename is used for this purpose. Here is the documentation of it on Material-UI.

CSS in JS documentation also explains this feature.

container: {
  //other styles
},
active: {
  "& $container": {
    background: "green",
    color: "#fff"
  }
}

Here one thing which is important that for referencing 'containerrule, it should be defined in the rules object. trying to use"& $containerwithout defining thecontainerrule inside themakeStyles` will not work.

Here is the working demo:

Edit nested rulename selector

I think this is what you are looking for $rulename

How to Use $ruleName to reference a local rule within the same style sheet

In your case i think the solution would be

const useStyles = makeStyles(theme => ({
  root: {
    margin: 5
  },
  container: {
    backgroundColor: 'red'
  },
  active: {
    .container: {
      backgroundColor: 'green'
    }
  }
});


   Which should compile to 

.root.container.active{} and on the target tag taking a example of button here

 <Button
  classes={{
    root: classes.root,
    container: classes.container,
    active: classes.active,
  }}>

Havent worked with MUI yet but even in vue or react the way this is achived is by setting a dynamic name on the tag that is targeted via script.

Related