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
Left/Right Float Button Inside Div
Half Pixel in Border Width Size It Is Not Showing
How to Tell Org-Mode to Embed My CSS File on HTML Export
Bootstrap Container-Fluid - Remove Margins The Right Way (Overflow)
Remove or Add Class in Angular
Is Browser Prefix Still Required for Linear-Gradient
Regression Testing for Styling and Layout of Web Applications
How to Do Horizontal Scroll in Ionic 3
Input[Type='Text'] CSS Selector Does Not Apply to Default-Type Text Inputs
How to Use The .Clearfix Class
How to Detect CSS Inheritance Source
Gooey CSS Effects with Contrast Parent
How to Enlarge The Svg Icon in Material-Ui Iconbuttons