Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple classNames with CSS Modules and React

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.

like image 964
Toby Avatar asked Jul 14 '16 18:07

Toby


People also ask

Can you have multiple Classnames in React?

We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.

How do I add multiple Classnames in material UI?

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.


2 Answers

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 : ''); 
like image 168
Chris Avatar answered Oct 03 '22 04:10

Chris


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> 
like image 20
bertybro Avatar answered Oct 03 '22 04:10

bertybro