Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Formik field with initial value React

CodeSandbox:

https://codesandbox.io/s/kind-fire-q4o45

Question:

Click on reset button and clear a field with value "initial value"


Attempts:

There are too many variants to reset form via:

  1. resetForm()
  2. setFieldValue(<your_field_name>, '')
  3. form.current.reset()

But this list doesn't helpful when you have initial value in formik field.


Snippet:

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = () => (
  <Formik onSubmit={({q}, {setSubmitting}) => {
    setSubmitting(false)
  }} initialValues={{q: 'initial value'}} render={({resetForm}) => (
    <Form>
      <Field name='q' />
      <button type="reset" onClick={() => resetForm()}>Reset</button> {/* <== Reset */}
    </Form>
  )}/>
)
like image 405
Arthur Avatar asked Oct 05 '19 16:10

Arthur


3 Answers

You're totally right - if you have some initial form state, the resetForm action will set the values to those initials. setFieldValue probably the only way to manually clear the field:

<button type="button" onClick={() => setFieldValue('q', '')}>
  Drop field
</button>

notice, type='reset' not need here...

In case when you need to drop multiple fields, take a look at this method: setValues({q: ''})

like image 185
Skyrocker Avatar answered Oct 13 '22 02:10

Skyrocker


You can now reset formik by

formik.resetForm({
    values: { name: 'Custom initial values', email: '' },
});

https://formik.org/docs/migrating-v2#resetform

like image 39
illiteratewriter Avatar answered Oct 13 '22 00:10

illiteratewriter


yes when you reset form values it will reset it to default value you can do the following

<Formik
  enableReinitialize
  onSubmit={(values, { setSubmitting }) => {
    values.q = '';
    setSubmitting(false);
  }}
  initialValues={{ q: "initial value" }}
  render={({ resetForm }) => (
    <Form>
      <Field name="q" />
      <button type="submit">
        Reset form
      </button>{" "}
      {/* <== Reset */}
    </Form>
  )}
/>

Hope it helps

like image 30
ibtsam Avatar answered Oct 13 '22 01:10

ibtsam