1

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0
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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

Following works:

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

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.