React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
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="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="form1"></div>
<div id="form2"></div>
JavaScript 1.7
var ValidatingForm = React.createClass({
registerField: function(field) {
var fields = this.state.fields;
fields.push(field);
this.setState({fields: fields});
},
submitForm: function(e) {
e.preventDefault();
var validForm = true;
this.state.fields.forEach(function(field) {
// just to make sure we don't crash if the field is missing the validation method
if(typeof field.isValid === "function") {
var validField = field.isValid();
validForm = validForm && validField;
}
});
if(validForm) {
console.log("form is valid");
// submit the form
} else {
console.log("form is invalid");
// don't submit the form :)
}
},
getInitialState: function() {
return {fields: []};
},
render: function() {
var newChildren = React.Children.map(this.props.children, function(child) {
// adding our on componentMounted callback
newChild = React.cloneElement(child, {onComponentMounted: this.registerField});
return newChild;
}, this);
return (<form onSubmit={this.submitForm}>{newChildren}</form>);
}
});
var TextField = React.createClass({
isValid: function() {
// random result, for demo purposes only
var valid = Math.random() * 10 > 5;
console.log("Validating ",this.props.name, "and returning ",valid);
return valid;
},
componentDidMount: function() {
if(this.props.onComponentMounted) {
this.props.onComponentMounted(this);
}
},
render: function() {
return (<input type="text" name={this.props.name} placeholder={this.props.name} />);
}
});
React.render(<ValidatingForm>
<TextField name="firstName" />
<TextField name="lastName"/>
<TextField name="email" />
<TextField name="password" />
...