Multiple classNames with CSS Modules and React

Toby picture Toby · Jul 14, 2016 · Viewed 28.5k times · Source

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.

Answer

Chris picture Chris · Jul 14, 2016

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 : '');