Skip to content

Instantly share code, notes, and snippets.

@kasprownik
Last active February 3, 2016 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasprownik/47aa3a28b3a2836184cc to your computer and use it in GitHub Desktop.
Save kasprownik/47aa3a28b3a2836184cc to your computer and use it in GitHub Desktop.
// src/components/Form.js
import React, {PropTypes} from 'react';
import without from 'lodash.without';
import assign from 'lodash.assign';
const noop = () => undefined;
export default React.createClass({
propTypes: {
children: PropTypes.node,
values: PropTypes.object,
update: PropTypes.func,
reset: PropTypes.func,
onSubmit: PropTypes.func
},
childContextTypes: {
update: PropTypes.func,
reset: PropTypes.func,
submit: PropTypes.func,
values: PropTypes.object,
registerValidation: PropTypes.func,
isFormValid: PropTypes.func,
},
getDefaultProps() {
return {
onSubmit: noop
};
},
validations: [],
registerValidation(isValidFunc) {
this.validations = [...this.validations, isValidFunc];
return this.removeValidation.bind(null, isValidFunc);
},
removeValidation(ref) {
this.validations = without(this.validations, ref);
},
isFormValid(showErrors) {
return this.validations.reduce((memo, isValidFunc) =>
isValidFunc(showErrors) && memo, true);
},
submit(){
if (this.isFormValid(true)) {
this.props.onSubmit(assign({}, this.props.values));
this.props.reset();
}
},
getChildContext() {
return {
update: this.props.update,
reset: this.props.reset,
submit: this.submit,
values: this.props.values,
registerValidation: this.registerValidation,
isFormValid: this.isFormValid
};
},
render() {
return (
<form>
{this.props.children}
</form>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment