Nested class in another selected class with makeStyles
Asked Answered
P

2

15

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>
Photomultiplier answered 18/12, 2019 at 0:28 Comment(0)
R
17

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>
Retraction answered 18/12, 2019 at 0:31 Comment(6)
and then how will the makeStyles be?Photomultiplier
your Jss is fine. No change is requiredRetraction
No, my makeStyles does not target .element when root is selected. Actually this is what I am missing.Photomultiplier
Sorry, just ignored my last comment. I have included the jss change as well nowRetraction
Hi @ChrisChen. I'm trying to do a similar thing, but couldn't able to achieve this and not able to figure out why. codesandbox.io/s/mystifying-swanson-yys5n , this is the demo. In this, I'm trying to change the icon color on hovering over the parent. can you please helpCheek
parent is listItemStyle classCheek
D
5

This answer is as an alternative to @Chris' answer.

You don't need to include another package to your project, as you can use 'clsx' from Material-UI. Here's how:

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

The clsx package comes with Material-UI when you install it.

import clsx from 'clsx';
const classes = useStyles(props);

...

<div className={clsx(classes.root, {
        [classes.selected]: elementSelected
    })}
>
    <div className={classes.element}>
    </div>
</div>
Dampen answered 5/4, 2020 at 9:46 Comment(1)
Just because a dependency is installed when you install something else, doesn't mean that you shouldn't also add it to your project directly. Your bundle generator (like Webpack) should only include one copy of the dependency, and your package manager should only download one copy, too.Suprarenal

© 2022 - 2024 — McMap. All rights reserved.