Allow EntityForm to be used standalone
authorFrank Bessou <frank.bessou@logilab.fr>
Fri, 05 May 2017 11:48:39 +0200
changeset 185 cfff71efc852
parent 184 d4466da07974
child 186 e44bcf04b4fd
Allow EntityForm to be used standalone It adds the ability to put <EntityForm /> in a react component by using either members or props. It is intended to become a stateless component.
src/components/Entity.js
--- a/src/components/Entity.js	Fri May 05 12:17:18 2017 +0200
+++ b/src/components/Entity.js	Fri May 05 11:48:39 2017 +0200
@@ -343,20 +343,17 @@
     },
 };
 
-class EntityForm extends React.Component {
+export class EntityForm extends React.Component {
 
     constructor(props, context) {
         super(props, context);
-        this.state = {schema: null, formData: null, uiSchema: uiSchema, _errors: null};
-        // To be implemented in derived class.
-        this.onSubmit = this.onSubmit.bind(this);
+        this.state = {schema: props.schema, formData: null, uiSchema: uiSchema, _errors: null};
     }
 
     render() {
-        if (this.state.schema === null) {
+        if (!this.state.schema) {
             return <div>loading...</div>;
         }
-        let errors = null;
         const renderValidationError = error => {
             let attrname;
             if (error.hasOwnProperty('source')) {
@@ -364,9 +361,9 @@
             }
             return [attrname, error.details || error.title].join(': ');
         };
-
-        if (this.state._errors !== null) {
-            errors = this.state._errors.map(
+        let errors = this.state._errors || this.props.errors;
+        if (errors) {
+            errors = errors.map(
                 error => (
                     <div className="alert alert-danger">
                         { renderValidationError(error) }
@@ -374,15 +371,22 @@
                 )
             );
         }
+        // Can be implemented in derived class.
+        const onSubmit = this.props.onSubmit || this.onSubmit.bind(this);
         return (
             <div>
                 {errors}
-                <FormWrapper {...this.state} onSubmit={this.onSubmit} />
+                <FormWrapper {...this.state} onSubmit={onSubmit} />
             </div>
         );
     }
 
 }
+EntityForm.propTypes = {
+    onSubmit: PropTypes.func,
+    schema: PropTypes.object,
+    errors: PropTypes.object,
+};
 
 EntityForm.contextTypes = {
     router: PropTypes.object,