Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
    </div>

// 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you’ve missed a bracket

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading