I'm using Material-UI's Checkbox component in my app, along with a related label.
I would like both the check-box and the label to be clickable, but I cannot use their FormControlLabel component (with control and label properties), which would ensure that clicking, because I want to use another component, instead of just text, for the label, and FormControlLabel doesn't seem to support it.
So, I'm thinking of triggering the click of the checbox when the label component gets clicked. Is there a proper way to do it?
You can wrap the Checkbox with a regular label to make the label toggle the checkbox.
<label> Label <Checkbox/></label>;
You can also control the Checkbox by using a piece of state for the checked prop and toggle that programmatically.
const { Checkbox } = window['material-ui'];
class App extends React.Component {
state = { isChecked: false };
toggle = () => {
this.setState(prevState => ({ isChecked: !prevState.isChecked }));
};
render() {
return (
<div>
<Checkbox checked={this.state.isChecked} onChange={this.toggle} />
<button onClick={this.toggle}>Toggle</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core/umd/material-ui.production.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With