React - using classNames with imported css

15,317

You can use the computed properties syntax of ES6/2015, for example:

import React from 'react';
import styles from './style.css';
import classNames from 'classnames';

export default class Menu extends React.Component {
  render() {
    const style = classNames({
      // This is a computed property, i.e. surrounded by []
      [styles.someClass]: true
    });
  }
}

But that is just for a single class, in these simple cases you could just do something like:

const style = this.state.active ? styles.someClass : '';

The classNames library is especially useful when combining multiple classes, like so:

import React from 'react';
import styles from './style.css';
import classNames from 'classnames';

export default class Menu extends React.Component {
  render() {
    const style = classNames(
      // add as many classes or objects as we would like here
      styles.foo,
      styles.bar,
      { [styles.someClass]: this.props.active }
    );
  }
}
Share:
15,317
Golan Kiviti
Author by

Golan Kiviti

Updated on June 12, 2022

Comments

  • Golan Kiviti
    Golan Kiviti almost 2 years

    I'm using react and I found this awesome library that helps you define css classes for components called classNames. I'm also using the webpack css-loader in order to import css into my component and when trying to use classNames with import css I get a syntax error.

    Here is my example:

    import React from 'react';
    import styles from './style.css';
    import classNames from 'classnames';
    
    export default class Menu extends React.Component {
        render() {
            let style = classNames({
                styles.someClass: true
            });
        }
    }
    

    How can I use both?