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.
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.
Eg:
<Formik
initialValues={initialValues}
...
>
{({ resetForm }) =>
...
<button type="reset" onClick={resetForm}>
Reset All
</button>
...
Codesandbox : https://codesandbox.io/s/7122xmovnq