Blog>
Snippets

Nested Form Fields

Illustrates the configuration and management of nested form fields, showcasing parent-child data relationships within a form.
import React from 'react';
import { Formik, Field, Form, useFormikContext } from 'formik';

const NestedInput = ({ name }) => {
  const { values, handleChange } = useFormikContext();

  return (
    <input
      type="text"
      name={name}
      value={values[name]}
      onChange={handleChange}
    />
  );
};

const MyForm = () => (
  <Formik
    initialValues={{ parent: '', child: { nestedField: '' } }}
    onSubmit={values => console.log(values)}
  >
    {() => (
      <Form>
        <Field name="parent" type="text" />
        <Field name="child.nestedField" component={NestedInput} />
        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);
This code illustrates how to use Formik with nested form fields in React. It uses the `useFormikContext` hook to access form values and methods for handling changes. The `NestedInput` component is used for the nested field, which demonstrates how to work with nested object structures within Formik. The `initialValues` object defines the structure of the form's data, including the nested `child` object with a `nestedField` attribute.