4

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?

1 Answer 1

14

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 }
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 ...
The classnames package works with plain old strings too. 👍 github.com/JedWatson/classnames

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.