3

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?

Golan Kiviti
  • 2,960
  • 6
  • 29
  • 55

1 Answers1

9

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 }
    );
  }
}
ctrlplusb
  • 11,352
  • 5
  • 48
  • 55
  • I have plain css clases next to my component ( not using import) so how can I use this classes. do I create a variable using template literals ?? I don't have to make the classes JS like (i.e btn-hover to btnHover) hopepully this makes sense ... – yokodev Apr 19 '18 at 23:32
  • The `classnames` package works with plain old strings too. https://github.com/JedWatson/classnames – ctrlplusb Apr 20 '18 at 11:14