Using CSS Modules in React How to Pass a Classname as a Prop to a Component

using css modules in react how can I pass a className as a prop to a component

From the docs:

Avoid using multiple CSS Modules to describe a single element.
https://github.com/gajus/react-css-modules#multiple-css-modules

@value colors: "../../styles/colors.css";
@value blue, black, red from colors;

.tile {
position: relative;
width: 100%;
padding-bottom: 100%;
}

.black {
composes: tile;
background-color: black;
}

.blue {
composes: tile;
background-color: blue;
}

.red {
composes: tile;
background-color: red;
}

Then <div className={styles[this.props.color]} should do the job, e.g:

render: function(){
// ES2015
const className = styles[this.props.color];

// ES5
var className = '';

if (this.props.color === 'black') {
className = styles.black;
}

return (
<div className={className}>
{this.props.children}
</div>
}

How to use props variable for css-modules className?

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

Passing css module as prop using babel-plugin-react-css-modules

I found a solution to this. By passing in the attributeNames option when configuring the plugin, I could specify the names of props that I want to be transformed, and what I want them to be transformed to.

{
"plugins": [
["@dr.pogodin/react-css-modules", {
attributeNames: {
altStyleName: "altClassName",
}
}]
]
}


Related Topics



Leave a reply



Submit