Search code examples
cssreactjscss-loaderclass-names

React - using classNames with imported css


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?


Solution

  • 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 }
        );
      }
    }