I want to add a Clear Button as a convenience to users:
constructor(props) {
this.emailInput = React.createRef();
}
<Field label="Email" name="email" ref={this.emailInput} onChange={onChange} component={TextField}/>
But get this:
Warning: Function components cannot be given refs. Attempts to access this ref will fail.
To reset particular fields, use setFieldValue
to set value to an empty string.
setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
Set the value of a field imperatively.
field
should match the key ofvalues
you wish to update. Useful for creating custom input change handlers.- Formik Documentation
Eg:
<Formik
initialValues={initialValues}
...
>
{({ setFieldValue }) =>
...
<button type="reset" onClick={() => setFieldValue('fieldName', '')}>
Reset This
</button>
...
To reset all fields, use resetForm
.
resetForm: (nextValues?: Values) => void
Imperatively reset the form. This will clear
errors
andtouched
, setisSubmitting
tofalse
,isValidating
tofalse
, and rerunmapPropsToValues
with the current WrappedComponent's props or what's passed as an argument.- Formik Documentation
Eg:
<Formik
initialValues={initialValues}
...
>
{({ resetForm }) =>
...
<button type="reset" onClick={resetForm}>
Reset All
</button>
...
Codesandbox : https://codesandbox.io/s/7122xmovnq
Formik has a built in method called resetForm which can be accessed like the other formik methods. In your form you probably have something like
<Formik
initialValues={something}
validationSchem={someSchema}
render={() => {
...some form stuff
}
}
/>
you can access the formik props inside that render method and do what you want with them:
<Formik
initialValues={something}
validationSchem={someSchema}
render={(props) => {
...some form stuff
<button type="button" onClick={() => props.resetForm()}>reset form</button>
}
}
/>
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