简体   繁体   中英

How to reset the form after submit or after clicking on cancel button using formik

const TextForm: React.FunctionComponent<Props> = (props) => { 

const formError = yup.object({
    name: yup.string().required("Required"),
  });
      const formValidation = (fieldName) => {
        return {
          invalid: !!form.errors[fieldName] && form.touched[fieldName],
          invalidText: form.errors[fieldName],
          onBlur: form.handleBlur,
        };
      };  
 const form = useFormik({
        initialValues: {
          name,
          id,
        },
        formValidation
        formError,
        validateOnChange: true,
        validateOnMount: true,
        initialTouched: {},
      });
  
    return(
    <React.Fragment>
    <form>
     <TextInput
                        id="text-input-2"
                        {...validation("name")}
                        type="text"
                        name = "name"
                        onChange={(event) => {
                          setName(event.target.value);
                          form.handleChange(event);
                        }}
                      />
    <TextInput
                        id="text-input-2"
                        {...validation("id")}
                        type="text"
                        name = "id"
                        onChange={(event) => {
                          setId(event.target.value);
                        }}
                      />
    <Button>Clear</Button>
    <Button>Submit</Button>
    </form>
    </React.Fragment>
    ) 
    }

Validations in my form are working fine. But if user does not enter any field, it comes with required warning. I am trying to clear/reset the form on Clear button click,but could not find any possible solution working. Can anyone help me with this.

A quick search of the Formik docs.

The Formik onSubmit and onReset are passed formikBag as their second argument, of which contains the resetForm action. The resetForm callback can be destructured from this formikBag object and used within your callback.

onSubmit onReset

const form = useFormik({
  initialValues: {
    name,
    id,
  },
  formValidation
  formError,
  validateOnChange: true,
  validateOnMount: true,
  initialTouched: {},
  onSubmit: (values, { resetForm }) => {
    // submission logic
    resetForm();
  },
  onReset: (values, { resetForm }) => resetForm(),
});

You also just need to ensure your form buttons have the correct button types so the form takes the correct action when clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM