I have a problem - I don't know how to change checkbox color using a color value from props. My idea was to give it via style attribute but I don't know how to toggle this. I'm using rc-switch and I want to change his background depending on Switch state. I have something like this now
<Switch style={{ backgroundColor: mainColor }}/>
I have a problem - I don't know how to change checkbox color using a color value from props. My idea was to give it via style attribute but I don't know how to toggle this. I'm using rc-switch and I want to change his background depending on Switch state. I have something like this now
<Switch style={{ backgroundColor: mainColor }}/>
but it set this color for both states and I want this swich to bee 'defaultColor' when is in off position.
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jul 2, 2017 at 18:49 Alan WołejkoAlan Wołejko 4522 gold badges5 silver badges21 bronze badges 1-
There is no
style
prop on the Switch Component, but there is aclassName
prop, which you can use to add your custom class. – webdeb Commented Jul 2, 2017 at 18:53
2 Answers
Reset to default 8There is no style prop on the Switch Component, but there is a className prop, which you can use to add your custom class.
If you are using sass:
.mySwitch {
&-black {
background-color: black;
}
&-yellow {
background-color: yellow;
}
}
Then programatically switch the class.
<Switch className={`mySwitch-${color}` ... />
Could be an option, I think.
You have to pass a callback to your <Switch>
ponent and then handle that event. You could write a ponent that wraps the original <Switch>
and switches color when it's state changes. It could look like this:
import React from 'react';
import Switch from 'rc-switch';
class ColorChangingSwitch extends React.Component {
constructor(props) {
super(props);
const {checked, defaultChecked} = props;
this.state = {
checked: checked || defaultChecked || false;
}
}
onChange = (checked) => {
// update your state
this.setState({
checked: checked,
});
this.props.onChange(checked);
}
render() {
const {onChange, className, checked, ...otherProps} = this.props;
const colorClassName = this.state.checked ? 'green' : 'red';
return (
<Switch
{...otherProps}
onChange={this.onChange}
checked={checked}
className={`${className} ${colorClassName}`}
/>
);
}
}
export default ColorChangingSwitch;
This is just a basic example. I didn't test it. You can still pass onChange
to that ponent and react to it with whatever you want. Also you could add a prop that defines which colors/classes it should set depending on it's state instead of hardcoding them.