React single, controlled checkbox field, with state management done correctly!
Using Reactjs, a single, controlled field. "Field" in this case refers to a group of input checkbox elements, matched on their name tag. Here, the state management is done correctly, i.e. at the highest component level. State is then passed down to the lower level components as props.
by Niranjan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<h3>React, single controlled input field, with state management done correctly!</h3>
<div id="main"></div>
CSS
label {
display: block
}
JavaScript 1.7
var CheckboxInput = React.createClass({
render: function () {
return (
<label>
<input type="checkbox"
name={this.props.name}
checked={this.props.checked}
onClick={this.handleChange}
value={this.props.value} />
{this.props.label}
</label>
);
},
handleChange: function(e) {
// Just a little preprocessing before passing upwards
this.props.handleChange(this.props.index, e.target.checked);
}
});
var CheckboxInputField = React.createClass({
getInitialState: function() {
var stateValues = this.props.question.values.slice();
for (var x = 0; x < stateValues.length; x++) {
// Add a checked state, if one has not been supplied
stateValues[x].checked = stateValues[x].checked || false;
}
return {
values: stateValues
};
},
render: function() {
var name = this.props.question.name;
var that = this;
var x = -1;
var mappedInputElements = this.state.values.map(function(data, key) {
x++;
return (
<CheckboxInput
name={name}
label={data.label}
index={x}
key={data.value}
value={data.value}
handleChange={that.handleFieldChange} />
);
});
return (
<div>
{mappedInputElements}
</div>
);
},
handleFieldChange: function(index, checked) {
// Make copy of state array values, update it, then set the state
var newStateValues = this.state.values.slice();
newStateValues[index].checked = checked;
this.setState({values: newStateValues});
}
});
var question = { name: "q1",
values: [
{label: "Apples", value: "apples"},
{label: "Bananas", value:...