Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 873
Golan Kiviti Avatar asked Jan 05 '23 21:01

Golan Kiviti


1 Answers

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 }
    );
  }
}
like image 193
ctrlplusb Avatar answered Jan 19 '23 10:01

ctrlplusb