Dynamic Css Via Prop Using Cssmodules With React Component
I'm learning how to use css modules with react, below is a working example of a checkbox here's what it looks like (pure HTML + CSS fiddle) without react. import React from 'react'
Solution 1:
You could create a different class composing the class you want to change the color:
.checkbox--styled-red {
composes: checkbox--styled;
background-image: url("data:image .... FF0000 ....");
}
And set it in the component when you get the matching props.color
:
importReactfrom'react'importCSSModulesfrom'react-css-modules'import styles from'./checkbox.css'functiongetStyleNameForColor(color) {
colorToStyleName = {
red: 'checkbox--styled-red'
};
return colorToStyleName[color] || 'checkbox--styled';
}
exportfunctionCheckbox (props) {
return<divstyleName="checkbox--container"><inputstyleName="checkbox"type="checkbox" {...props}/><spanstyleName={getStyleNameForColor(props.color)}></span></div>
}
exportdefaultCSSModules(Checkbox, styles)
Better yet, use classnames instead of getStyleNameFor(color)
.
Post a Comment for "Dynamic Css Via Prop Using Cssmodules With React Component"