Skip to content

Instantly share code, notes, and snippets.

@nkt
Created October 16, 2015 13:32
Show Gist options
  • Save nkt/7ffdc28e2fdeca0c4574 to your computer and use it in GitHub Desktop.
Save nkt/7ffdc28e2fdeca0c4574 to your computer and use it in GitHub Desktop.
const React = require('react');
const Form = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired,
defaultValue: React.PropTypes.object.isRequired,
children: React.PropTypes.node.isRequired
},
getInitialState() {
return Object.assign({}, this.props.defaultValue);
},
componentWillReceiveProps(props) {
this.setState(Object.assign({}, props.defaultValue));
},
onSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state);
},
onChange(name, value) {
this.setState({
[name]: value
});
},
renderChildren(children) {
return React.Children.map(children, (Component) => {
if (!React.isValidElement(Component)) {
return Component;
}
if (Component.type.isFormChild) {
return React.cloneElement(Component, {
onChange: this.onChange,
value: this.state[Component.props.name]
});
}
if (Component.props.children) {
return React.cloneElement(Component, {}, this.renderChildren(Component.props.children));
}
return Component;
});
},
render() {
return (
<form className="form" onSubmit={this.onSubmit}>
{this.renderChildren(this.props.children)}
</form>
);
}
});
module.exports = Form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment