Cloud tech Cloud tech - 1 year ago 142
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download