A simple way of doing this is to set up a styles object in your Checkbox component to define primary and success, and info styles and add a style attribute to the parent div that updates its style based on the type (passed in through props) when the box is checked.
So there are three key things:
1) We pass in a type property to the component. In the component we assign that value to a new type property in state.
2) We set up a styles object that contains the background colours for each different checkbox type
3) We assign a colour object from the styles object if checked is true.
Let's break down how that works:
style={checked ? { width: '50px', ...styles[type] } : { width: '50px' }}
The style attribute accepts an object. In the case where checked is false we want to return an object that defines the width, but if checked is true we want to return an object with the width definition and the colour definition from styles. In the above line I've used a ternary operation that translates as:
if (checked) use the combined width object and styles[type] object (else) just use the object with the width definition`.
const { Component } = React;
// App.js
function App() {
return (
<div className="App">
<Checkbox type="primary" />
<Checkbox type="success" />
<Checkbox type="info" />
</div>
);
}
// Checkbox.js
// Style definitions
const styles = {
primary: { backgroundColor: 'blue' },
success: { backgroundColor: 'green' },
info: { backgroundColor: 'cyan' }
}
class Checkbox extends Component {
constructor(props) {
super(props);
// Set a new type property in state and assign the
// props value of type to it
this.state = { type: props.type, checked: false };
this.onChange = this.onChange.bind(this);
}
onChange = () => {
this.setState({ checked: !this.state.checked });
}
render() {
// Destructure the type and checked properties from state
const { type, checked } = this.state;
return (
<div className="checkbox" onClick={this.onChange}>
{/* If the box is checked set a width of 50px and apply the styles for that type */}
{/* Otherwise just set a width of 50px */}
<div
className="checkbox-box"
style={checked ? { width: '50px', ...styles[type] } : { width: '50px' }}
>
<span className="checkbox-box-mark" >
<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
<path d="M21.33,57.82,0,36.53l5.87-5.87L21.33,46.09,58.13,9.36,64,15.23,21.33,57.82"/>
</svg>
</span>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/>
Further reading