To show nested forms using Formik, you can utilize the FieldArray
component provided by Formik. The FieldArray
component allows you to work with arrays of form fields and provides a convenient way to render and manage nested forms.
Here's a step-by-step guide to showing nested forms using Formik and FieldArray
:
Install Dependencies: Make sure you have installed Formik and Yup (for form validation) in your project.
bashnpm install formik yup # or yarn add formik yup
Import Required Modules: Import the necessary modules from Formik and Yup in your component.
jsximport React from 'react'; import { Formik, Form, Field, FieldArray } from 'formik'; import * as Yup from 'yup';
Create Form Schema: Define the validation schema for your form using Yup. This step is optional but recommended for data validation.
jsxconst validationSchema = Yup.object().shape({ // Define your validation schema here });
Render the Form: Use the
Formik
component to wrap your form and define the initial form values and form submission logic.jsxconst initialValues = { // Define your initial form values here }; const handleSubmit = (values) => { // Handle form submission here }; const MyForm = () => { return ( <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={handleSubmit} > {({ values }) => ( <Form> {/* Render your form fields and nested form using Field and FieldArray */} </Form> )} </Formik> ); };
Use Field and FieldArray Components: Within the
Form
component, use theField
component for regular form fields and theFieldArray
component to handle nested forms.jsxconst MyForm = () => { return ( <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={handleSubmit} > {({ values }) => ( <Form> {/* Regular form field */} <label htmlFor="name">Name:</label> <Field type="text" name="name" id="name" /> {/* Nested form using FieldArray */} <FieldArray name="friends"> {({ push, remove }) => ( <div> {values.friends.map((friend, index) => ( <div key={index}> {/* Nested form fields */} <label htmlFor={`friends.${index}.name`}>Friend's Name:</label> <Field type="text" name={`friends.${index}.name`} id={`friends.${index}.name`} /> {/* Button to remove the nested form */} <button type="button" onClick={() => remove(index)}> Remove Friend </button> </div> ))} {/* Button to add a new nested form */} <button type="button" onClick={() => push({ name: '' })}> Add Friend </button> </div> )} </FieldArray> {/* Submit button */} <button type="submit">Submit</button> </Form> )} </Formik> ); };
In this example, we have a form with a regular form field for the user's name and a nested form for entering their friends' names. The
FieldArray
component is used to handle the array of friends, and thepush
andremove
methods are used to add or remove friends dynamically.
By using the FieldArray
component in Formik, you can easily manage nested forms within your main form and handle arrays of form fields more effectively.