CodeSandbox:
https://codesandbox.io/s/kind-fire-q4o45
Question:
Click on reset button and clear a field with value "initial value"
Attempts:
There are too many variants to reset form via:
resetForm()
setFieldValue(<your_field_name>, '')
form.current.reset()
But this list doesn't helpful when you have initial value in formik field.
Snippet:
import React from 'react'
import {Formik, Form, Field} from 'formik'
const Search = () => (
<Formik onSubmit={({q}, {setSubmitting}) => {
setSubmitting(false)
}} initialValues={{q: 'initial value'}} render={({resetForm}) => (
<Form>
<Field name='q' />
<button type="reset" onClick={() => resetForm()}>Reset</button> {/* <== Reset */}
</Form>
)}/>
)
You're totally right - if you have some initial form state, the resetForm
action will set the values to those initials. setFieldValue
probably the only way to manually clear the field:
<button type="button" onClick={() => setFieldValue('q', '')}>
Drop field
</button>
notice, type='reset'
not need here...
In case when you need to drop multiple fields, take a look at this method:
setValues({q: ''})
You can now reset formik by
formik.resetForm({
values: { name: 'Custom initial values', email: '' },
});
https://formik.org/docs/migrating-v2#resetform
yes when you reset form values it will reset it to default value you can do the following
<Formik
enableReinitialize
onSubmit={(values, { setSubmitting }) => {
values.q = '';
setSubmitting(false);
}}
initialValues={{ q: "initial value" }}
render={({ resetForm }) => (
<Form>
<Field name="q" />
<button type="submit">
Reset form
</button>{" "}
{/* <== Reset */}
</Form>
)}
/>
Hope it helps
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