How to use props variable for css-modules className?

Is it possible to use a props variable for a css-modules className?

// Component.js
import styles from "./Component.module.scss"

const Component = ({ color }) => 
    <div className={`${styles.component}` `${styles.color}`>

// Component.module.scss
.component { border: 1px black solid; }
.red { color: red; }
.green { color: green; }

Then I could use the Component like so:

// App.js
<Component color="red" />
<Component color="green" />

And have the two Components be red and green respectively.

>Solution :

I think you’ve missed a bracket

const Component = ({ color }) => {
    const cssColor = color;
    return (
        <div className={`${styles.component}` `${styles[cssColor]}`}>

To use Component level CSS you can get it loaded in your webpack as using a loader (Reference)

When using webpack, you can add the loader and also include the module to your webpack.config.js in other to make CSS modules work with Webpack.

test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 

Alternatively, you could use a library called classnames

Leave a Reply