I have below a working component that allows for a checkbox all and checkboxes. It works perfectly. However I hate the idea that I'm stuck carrying all of this code around every time I want to use this feature. I'm looking for a way within react to make this modular? Is this
It doesn't modularize the entire functionality of the "input checked all" functionality in one place. I have to move the getInitialState variables and changeHandlers with each usage.
I think of it like if the "input checkbox all" functionally was native within HTML, how would we use it? We would need only supply the attributes to the elements and they would reference each other and all of the handlers would occur under the hood, it would be simple to use. My goal with this example is to have HTML level simplicity. The code I show above doesn't achieve that because it's tied down to function handlers and state initializers. Does react provide a way of abstracting this?
Below is my desired API for this component.
The main problems are:
- The component functionality is indifferent to the parent, meaning the paren't doesn't need to store the information for the handlers and state.
- The code currently manually tracks state for each checkbox, meaning there's no way to dynamically find how many of an a checkbox is in the DOM without stating it.
- Overall modularity and ease-of use.
Here's the code:
var InputCheckbox = React.createClass({
getDefaultProps: function () {
return {
checked: false
}
},
render: function () {
return (
<input
checked={this.props.checked}
type='checkbox'
{...this.props}/>
)
}
})
var Test = React.createClass({
getInitialState: function () {
return {
checked: [false, false, false]
}
},
selectAll: function (event) {
// Set all checked states to true
this.setState({
checked: this.state.checked.map(function () {
return event.target.checked
})
})
},
handleChange: function (index, event) {
var checked = this.state.checked
checked[index] = event.target.checked
this.setState({
checked: checked
})
},
render: function () {
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>
)
}
})
React.render(<Test/>, document.body)
Ideally I can just use it like this:
var Checkbox = require('./Checkbox')
var Test = React.createClass({
render: function () {
return (
<div>
<Checkbox id="alpha"/>
<Checkbox htmlFor="alpha"/>
<Checkbox htmlFor="alpha"/>
<Checkbox htmlFor="alpha"/>
</div>
)
}
})
checkedstate from the store and passes it into the checkbox as a prop.