Search code examples
reactjsrefformik

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.


Solution

  • 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