I'm using the following code to dynamically set a className in a React component based upon a boolean from props:
<div className={this.props.menuOpen ? 'inactive' : 'active'}> ... </div>
However, I'm also using CSS Modules, so now I need to set the className to:
import styles from './styles.css';
<div className={styles.sideMenu}> ... </div>
I'm having trouble with this - I tried using classnames to gain more control with multiple classes, but because I need the end result to be that the className is set to both styles.sideMenu
AND styles.active
(in order for CSS Modules to kick in) I'm unsure how to handle this.
Any guidance greatly appreciated.
We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.
To add multiple classes in React Material UI using the classes props, we can use the classnames package. We call makeStyles with an object with the class names as the property names. And we set each property to an object with the CSS styles as the value. Next, we call useStyles to return the classes object.
Using classnames and es6:
let classNames = classnames(styles.sideMenu, { [styles.active]: this.props.menuOpen });
Using classnames
and es5:
var classNames = classnames(styles.sideMenu, this.props.menuOpen ? styles.active : '');
Bit late to the party here, but using string templates works for me - you could move the ternary operator out to a const if you'd like as well:
<div className={`${styles.sideMenu} ${this.props.menuOpen ? styles.inactive : styles.active}`> ... </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With