Reputation: 3357
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
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
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