5

I want to pass an array of styles to a React Component using postcss-loader and css modules. My webpack.config.file for compiling css files looks like this:

loaders: [
    'style-loader', 
    'css-loader?modules&importLoaders=1&localIdentName[name]__[local]___[hash:base64:5]',
    'postcss-loader'
],

My React Component file looks like this:

import styles from './cssFile.css';
class Component extends React.Component{
    render(){
       return(
           <div className={[styles.spinner, styles.spinner_2]}></div>
       )
    }   
}

Whenever I pass only one style to className it loads it correctly but when I pass an array it does not resolve any of them. Instead it concatenates it with a comma on the compile class name.

How can I pass several styles to an element?

1
  • It might just be in the code you've pasted in SO but your class syntax is invalid, you need to define a render method and return the React element. Other than that @ori-drori is correct in saying className must be a string. Commented Oct 3, 2016 at 12:44

2 Answers 2

6

React's className expects a string of class names, and not an array:

import styles from './cssFile.css';
class Component extends React.Component{
    <div className={ [styles.spinner, styles.spinner_2].join(' ') }></div>
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use classnames for this. For example:

import styles from './cssFile.css';
import classNames from 'classnames';

class Component extends React.Component {
  render() {
    return <div className={classNames(styles.spinner, styles.spinner_2)}></div>
  }
}

From the classnames documentation:

The classNames function takes any number of arguments which can be a string or object. If the value of the key is falsy, it won't be included in the output.

Comments

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.