Created
October 16, 2015 13:32
-
-
Save nkt/7ffdc28e2fdeca0c4574 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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