How to disabled the submit button in formik ?
const validation = (values) => {
let error = {};
if (!values.name) {
error.name = 'Name is required';
}
if (!values.password) {
error.phone = 'Password is required';
}
return error;
}
const validateSkills = (skill) => {
let error;
if (!skill) {
error = 'Skill Required'
}
return error;
}
let initialValues = {
name: '',
password: '',
skills: ['']
};
const onSubmit = (values) => {
console.log('--values--', values)
}
<Formik
initialValues={initialValues}
validate={validation}
onSubmit={onSubmit}
validateOnMount
>
{
(formik)=>{
return(
<Form>
<Field name="name"/>
<button type='submit' disabled={!formik.isValid} >Submit</button>
</Form>
)
}
}
</Formik>
When we load the page and as soon as the form mount on the DOM formik runs the validation on each field and populates the error object, by default formik does not do that.
validateOnMount
we are enabling that feature.validateOnMount
is good if you have a form with less fields.- All the fields are having validation so if the user don't fill value to any field then we will show the validation error message
- While submitting the form we should prevent the user to click the submit button multiple time , so we need to disabled it.
So, we have to disabled the submit button when there is any validation error and while submitting , to achieve that formic provides two properties
isValid
and isSubmitting
the initial value of isValid
is true and the initial value of isSubmitting
is false , so when there is any error the the isValue
gets changed to false.
and when we submit the form the the value of isSubmitting
gets changed from false to true. But if you want to reset the value of isSubmitting that you have to do in onSubmit
function
onSubmit() function provides two parameters first param is value and the second one is props , props has setSubmitting(false) to reset isSubmitting
<button disabled={!formik.isValid || formik.isSubmitting} type='submit'>Submit</button>
const onSubmit = (values , props) => {
console.log('--values--', values);
props.setSubmitting(false);
}
Complete Code :
import { Form, Formik, Field, ErrorMessage, FieldArray } from 'formik';
const Index = () => {
const validation = (values) => {
let error = {};
if (!values.name) {
error.name = 'Name is required';
}
return error;
}
let initialValues = {
name: '',
};
const onSubmit = (values, props) => {
console.log('--values--', values);
props.setSubmitting(false)
}
return (
<Formik
initialValues={initialValues}
validate={validation}
onSubmit={onSubmit}
>
{
(formik) => {
return(
<Form>
<Field name="name" />
<ErrorMessage name='name' />
<button type='submit' disabled={!formik.isValid || formik.isSubmitting} >Submit</button>
</Form>
)
}
}
</Formik>
)
}
export default Index;