Cloud tech Cloud tech - 7 months ago 54
Javascript Question

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

_toggleValue: function(state) {
//?? how to do it

render() {
<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)} />

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


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.