React input checkbox select all component
I think there could be some modifications to your implementation to achieve the desired results in a more React'esque form.
What you should get rid of first, is the InputCheckboxAll
checkbox class, and the allChecked
prop of the InputCheckbox
class. A checkbox is a relatively dumb element, it should not know about concepts such as Everything is selected
.
Instead, the checkbox should be implemented as an item that is simply either checked or unchecked.
var InputCheckbox = React.createClass({
getDefaultProps: function () {
return {
checked: false
}
},
render: function () {
return (
<input
checked={this.props.checked}
type='checkbox'
{...this.props}/>
)
}
})
The state of your app (concepts such as All Selected) should be managed from the main App, keeping lower level elements stateless. The state of the main app can simply represent the checked status of each of your checkboxes:
getInitialState: function () {
return {
// 3 checkboxes, all initialized as unchecked
checked: [false, false, false]
};
},
Now, you can recreate the render function to draw 3 checkboxes, plus your select all checkbox. Each <InputCheckbox>
can be binded to its own data in the this.state.checked
array. When the <Inputcheckbox>
changes, we bind an index to the change handler, so we know which array element to modify.
render: function () {
// Recalculate if everything is checked each render, instead of storing it
var isAllChecked = this.state.checked.filter(function(c) {
return c;
}).length === this.state.checked.length;
return (
<div>
Select All: <InputCheckbox
onChange={this.selectAll}
checked={isAllChecked}/><br/>
<InputCheckbox
checked={this.state.checked[0]}
onChange={this.handleChange.bind(this, 0)}/><br/>
<InputCheckbox
checked={this.state.checked[1]}
onChange={this.handleChange.bind(this, 1)}/><br/>
<InputCheckbox
checked={this.state.checked[2]}
onChange={this.handleChange.bind(this, 2)}/><br/>
</div>
)
}
You don't need to store any state related to All Selected. Instead, it would be better to recalculate if everything is selected or not during every render. When the Select All
checkbox is checked, we simply set every element of this.state.checked
to true.
This also has the advantage of when you manually select all the checkboxes, the select all checkbox will check itself.
Here's a sample implementation: https://jsfiddle.net/rsupvxry/