How to add a Clear Button on a Formik Textfield

16,679

Solution 1

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 of values 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 and touched, set isSubmitting to false, isValidating to false, and rerun mapPropsToValues 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

Solution 2

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>
    }
  }

/>

Solution 3

you can try to set a reset button in your form, e.g

<form>
 <Field label="Email" name="email" onChange={onChange} component={TextField}/>
 <input type="reset" value="Reset">
</form>

I took the example here, it has to reset all of the inputs in the form

Share:
16,679
Mark Simon
Author by

Mark Simon

Updated on July 07, 2022

Comments

  • Mark Simon
    Mark Simon almost 2 years

    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.