Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React, how to use one method to toggle states for multiple checkboxes values

 _toggleValue: function(state) {
    //?? how to do it 
    //this.setState(???);
  },

render() {
  <div>
    <form>
      <input type="checkbox" onChange={this._toggleValue.bind(null, this.state.a)} />
      <input type="checkbox" onChange={this._toggleValue.bind(null, this.state.b)} />
      <input type="checkbox" onChange={this._toggleValue.bind(null, this.state.c)} />
    </form>
  </div>
}

There are quite lot checkboxes in the form, currently, what I am doing is to define one method for each checkbox. How can I define one method which can be used by all the checkboxes.

Many thanks in advance

like image 986
Xiaohe Dong Avatar asked Sep 15 '25 05:09

Xiaohe Dong


1 Answers

You could use the LinkedStateMixin.

Your checkboxes would look something like this:

<input type='checkbox' checkedLink={this.linkState('a')}/>
<input type='checkbox' checkedLink={this.linkState('b')}/>
<input type='checkbox' checkedLink={this.linkState('c')}/>

This will automatically keep the values of the checkboxes a, b and c up to date with the state variables.

like image 121
Clarkie Avatar answered Sep 16 '25 18:09

Clarkie