Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Clear Button on a Formik Textfield

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.

like image 927
Mark Simon Avatar asked Dec 07 '22 12:12

Mark Simon


2 Answers

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

like image 170
Dani Vijay Avatar answered Dec 11 '22 12:12

Dani Vijay


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

/>
like image 31
Aaron Ross Avatar answered Dec 11 '22 11:12

Aaron Ross