Nested class in another selected class with makeStyles

Aladdin Mhemed picture Aladdin Mhemed · Dec 18, 2019 · Viewed 10.2k times · Source

I need to know how to target 'element' when root is selected

This is makeStyles:

const useStyles = makeStyles(theme => ({
   root:{
      '&.selected': {
      }
   },
   element: {
   }
})

This is jsx

<div className={`${classes.root} ${elementSelected ? 'selected : ''}`}>
  <div className={classes.element}>
  </div>
</div>

Answer

Chris Chen picture Chris Chen · Dec 18, 2019

You can use https://www.npmjs.com/package/classnames to achieve this.

const useStyles = makeStyles(theme => ({
   root:{
      '&.selected $element': {
      }
   }
})

And your JSX

import classNames from 'classnames';

...

<div className={classNames(classes.root, elementSelected ? 'selected : '')}>
  <div className={classes.element}>
  </div>
</div>