Cloud tech Cloud tech - 3 months ago 27
Javascript Question

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

Answer

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.