redux-form: How to disable submit button if at least one Field is not valid?

Christof Kälin picture Christof Kälin · May 3, 2017 · Viewed 16.3k times · Source

I'm rendering the below simple form using redux-form and it's working nicely. Now, I'd like to have the submit button disabled in one more situation: If any of the Field's has an error (i.e. it's meta.error is set).

From lokking into the docs, I suppose it is not possible for the surrounding <form> to know if its <Field> components have an error. Maybe anyone has an idea, how to solve it as easy as using disabled={hasErrors || submitting || pristine}

const EditBlogEntryForm = ({ onSubmit, reset, handleSubmit,
                         pristine, submitting, ...rest }) => {
    console.log('rest: ', rest);
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <div className="form-group">
                <Field name="title"
                    type="text"
                    component={renderField}
                    label="Titel"
                    className="form-control"
                    placeholder="Titel eingeben..." />
            </div>
            <div className="form-group">
                <Field name="text"
                    component={renderTextArea}
                    label="Text"
                    className="form-control"
                    placeholder="Textinhalt eingeben..." />
            </div>  
            <div className="form-group">
                <Field name="image"
                    type="text"
                    component={renderField}
                    label="Bild-URL:"
                    className="form-control"
                    placeholder="Bildadresse eingeben..." />
            </div>  
            <div>
                <button type="submit" className="btn btn-default"
                    disabled={submitting || pristine}>
                    Blogeintrag speichern
                </button>
                <button type="button" className="btn btn-default"
                    disabled={pristine || submitting}
                    onClick={reset}>
                    Formular leeren
                </button>
            </div>
        </form>
    );
};

Answer

masoud soroush picture masoud soroush · Dec 3, 2017

Don't abuse state you need just using this.props for each setState Component one more time will be render

const {invalid} = this.props

return(
<button type="submit" className="btn btn-default"
     disabled={invalid|| submitting || pristine}>
     Blogeintrag speichern
 </button>)

More Document: https://redux-form.com/6.0.0-alpha.4/docs/api/props.md/