Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically check a Material-UI check-box?

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?

like image 399
Jānis Elmeris Avatar asked Oct 17 '22 06:10

Jānis Elmeris


1 Answers

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>
like image 148
Tholle Avatar answered Oct 21 '22 13:10

Tholle