Ben
Ben

Reputation: 3357

Reset a React Native Formik form from outside the form

I know you can use resetForm in Formik to reset the form in onSubmit. However, is there a way to reset it programmatically by assigning it a ref and calling a rest form method on it somehow?

Upvotes: 13

Views: 11643

Answers (2)

Hashan Shalitha
Hashan Shalitha

Reputation: 875

Here is my approach using useFormik hook.

import { useFormik } from "formik";

export default function LoginScreen() {

  const formik = useFormik({
    initialValues: {
      email: ""
    },
    onSubmit: (val) => console.log(val),
  });


  return(
    <TextInput
      onChangeText={formik.handleChange("email")}
      value={formik.values.email}
      placeholder="Enter your email"
    />

    {formik.touched.email && <ErrorText>{formik.errors.email}</ErrorText>}

    <Button onPress={formik.handleSubmit}>Login</Button>

    <Button onPress={formik.resetForm}>Clear</Button>
  );
}

Upvotes: 1

Hassan Kandil
Hassan Kandil

Reputation: 1866

there is a prop called innerRef to make ref for a formik form

<Formik
   innerRef={(p) => (this.formik = p)}
/>

then use it like this:

onPress={() => this.formik.resetForm()}

Or with a functional component:

const formikRef = useRef();
<Formik
  innerRef={formikRef}
  ...
/>

and then use with

onPress={() => formikRef.current?.resetForm()}

Upvotes: 28

Related Questions