Formik is a popular React library for handling form state management and validation. To reset a form in Formik, you can use the resetForm function from Formik. resetForm is one of the helper methods for Formik forms, typically available within the Formik component or the useFormik hook.
Here are several scenarios for using the resetForm method to reset a form:
Using the Formik Component
If you are using the Formik component, you can access the resetForm method within the render prop or the children function via Formik's rendering properties.
jsximport { Formik, Form, Field } from 'formik'; const MyForm = () => ( <Formik initialValues={{ name: '' }} onSubmit={(values, actions) => { // Submission logic actions.resetForm(); }} > {({ resetForm }) => ( <Form> <Field name="name" type="text" /> <button type="button" onClick={() => resetForm()}> Reset Form </button> <button type="submit">Submit</button> </Form> )} </Formik> );
Using the useFormik Hook
If you are using the useFormik hook, you can directly access the resetForm method from the returned Formik instance.
jsximport React from 'react'; import { useFormik } from 'formik'; const MyForm = () => { const formik = useFormik({ initialValues: { name: '' }, onSubmit: values => { // Submission logic formik.resetForm(); }, }); return ( <form onSubmit={formik.handleSubmit}> <input name="name" type="text" onChange={formik.handleChange} value={formik.values.name} /> <button type="button" onClick={() => formik.resetForm()}> Reset Form </button> <button type="submit">Submit</button> </form> ); };
Resetting to Specific Values
The resetForm method also accepts an optional parameter. If you want to reset the form to specific values instead of the initial values, you can do the following:
jsxresetForm({ values: { name: 'Specific Value' } });
With this approach, when you trigger the resetForm method, the form's values will be reset to the provided values.
The above code assumes you have already installed and imported the Formik-related modules, and set up appropriate initial form values and submission handling logic. In actual development, please adjust the logic based on specific requirements.