React single, controlled checkbox field, correct
Using Reactjs, a single, controlle element done correctly. Click on the checkbox and the state changes, the input re-renders
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 element, correct</h3>
<div id="main"></div>
JavaScript 1.7
var CheckboxInput = React.createClass({
getInitialState: function () {
return {
checked: this.props.checked || false
};
},
render: function () {
return (
<label>
<input type="checkbox"
name={this.props.name}
checked={this.state.checked}
onClick={this.handleClick}
value={this.props.value} />
{this.props.label}
</label>
);
},
handleClick: function(e) {
this.setState({checked: e.target.checked});
}
});
var question = { label: "Apples", name: "q1", value: "apples" };
React.render(<CheckboxInput label={question.label} name={question.name} />, document.getElementById("main"));