cosmo-ui
Version:
Common React components
72 lines • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var actions_1 = require("../actions");
var selectors_1 = require("../selectors");
var react_redux_1 = require("react-redux");
var PropTypes = require("prop-types");
var FormComponent = (function (_super) {
tslib_1.__extends(FormComponent, _super);
function FormComponent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Prevent the native onSubmit event from triggering
* @param e
*/
_this.onSubmit = function (e) {
e.preventDefault();
var _a = _this.props, formData = _a.formData, name = _a.name, onSubmit = _a.onSubmit, submitFormValid = _a.submitFormValid, submitFormInvalid = _a.submitFormInvalid;
var keys = Object.keys(formData);
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var field = keys_1[_i];
if (formData[field] && !formData[field].valid) {
// dispatch an action to say the form is submitted but invalid
// and end the submission process here
return submitFormInvalid(name, formData);
}
}
// dispatch an action to say the form is submitted and valid
submitFormValid(name, formData);
// now call the onsubmit handler with the data
if (onSubmit) {
onSubmit(formData);
}
};
return _this;
}
FormComponent.prototype.componentWillUnmount = function () {
this.props.destroyForm(this.props.name);
};
/**
* Make the form name available to child components
* without explicitly passing it down to every one
*/
FormComponent.prototype.getChildContext = function () {
return {
formName: this.props.name,
};
};
/**
* Render a form tag
*/
FormComponent.prototype.render = function () {
var _a = this.props, name = _a.name, id = _a.id, children = _a.children, className = _a.className, style = _a.style;
return (React.createElement("form", { name: name, id: id, className: className, style: style, onSubmit: this.onSubmit }, children));
};
return FormComponent;
}(React.Component));
FormComponent.childContextTypes = {
formName: PropTypes.string,
};
var mapStateToProps = function (state, ownProps) { return ({
formData: selectors_1.getForm(state, ownProps.name),
}); };
var mapDispatchToProps = {
resetForm: actions_1.resetForm,
destroyForm: actions_1.destroyForm,
submitFormValid: actions_1.submitFormValid,
submitFormInvalid: actions_1.submitFormInvalid,
};
exports.Form = react_redux_1.connect(mapStateToProps, mapDispatchToProps)(FormComponent);
//# sourceMappingURL=form.js.map