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>
);
};
Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.
To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.
pristine means that no fields in the form have been modified yet. Perhaps you won't be able to find an exact definition of it in docs, but there is a similar terminology in Angular. You can find some details here or here. submitting , as the name suggests, means that the form is in process of submitting.
Redux forms already passes lots of properties into the form. One is invalid
. That's what I am using to determine if any of the field validations failed and then disable submit.
https://redux-form.com/6.0.0-alpha.4/docs/api/props.md/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With