osmancakirio
osmancakirio

Reputation: 519

Formik Field Array for Nested fields

I want to render a Form with nested fields inside a <FieldArray /> component. But when I create the Form Fields based on the index, I get extra fields that I don't want. As shown below:

friends_list

As you can see Julia and 28 should be on the same row. But instead, I get four fields in two rows. Empty fields are also writing the age and name values when typed. I don't get why this is happening. But I don't want them. Below you can see the code for the component. I also created a sandbox to work on it in here codesandbox.

Note: I want these nested Fields so the structure of my array friends: [{ name: "Julia" }, { age: "28" }] is important to the question.

import React from "react";
import { Formik, Form, Field, FieldArray } from "formik";

// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ friends: [{ name: "Julia" }, { age: "28" }] }}
      onSubmit={values =>
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500)
      }
      render={({ values }) => (
        <Form>
          <FieldArray
            name="friends"
            render={arrayHelpers => (
              <div>
                {values.friends.map((friend, index) => (
                  <div key={index}>
                    <Field name={`friends[${index}].name`} />
                    <Field name={`friends.${index}.age`} />
                    <button
                      type="button"
                      onClick={() => arrayHelpers.remove(index)}
                    >
                      -
                    </button>
                  </div>
                ))}
                <button
                  type="button"
                  onClick={() => arrayHelpers.push({ name: "", age: "" })}
                >
                  +
                </button>
              </div>
            )}
          />
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      )}
    />
  </div>
);

export default FriendList;

Upvotes: 1

Views: 4195

Answers (1)

demkovych
demkovych

Reputation: 8827

You have wrong initial values, should be like:

[{ name: "Julia", age: "27" }]

Instead you passed 2 array items

Upvotes: 1

Related Questions