Chris
Chris

Reputation: 668

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.

Upvotes: 1

Views: 7956

Answers (3)

Mehdi Jeyrani
Mehdi Jeyrani

Reputation: 1

import styles from "./component.module.css";

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

I think this operation works better

Upvotes: 0

Ankit Sanghvi
Ankit Sanghvi

Reputation: 527

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

Upvotes: 2

Chris
Chris

Reputation: 668

Following works:

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

Upvotes: -1

Related Questions