React Survey App - state in wrong place
React Survey App, but with state still stuck down at the CheckboxInputField level. We need to move it higher up.
by BrownieBoy
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>Survey App - state in wrong place</h3>
<div id="main"></div>
CSS
label {
display: block
}
.inputFieldWrapper {
margin: 0 5px 35px 5px;
border: 1px solid lightgray;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.inputFieldWrapper p {
margin: 0 0 4px 0;
}
.inputFieldWrapper input {
margin-right: 5px;
}
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 className="inputFieldWrapper">
<p>{this.props.question.blurb}</p>
{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 CheckboxInputFields = React.createClass({
render: function() {
var...