TanStackT
TanStack5mo ago
38 replies
sacred-emerald

Nesting Field Array in Child Component

Hi folks!

I'm trying to create an array field with the ability to to add items to the array. There is an example of how to do this in the docs (https://tanstack.com/form/latest/docs/framework/react/guides/arrays#full-example) but the docs always seem to assume that I'm rendering all my fields in the root form component where the useForm hook is called.

<form.Field name="people" mode="array">
  {(field) => {
    // I want to move everything in this return to another component
    return (
      <div>
        {field.state.value.map((_, i) => {
          return (
            <form.Field key={i} name={`people[${i}].name`}>
              {(subField) => {
                return (
                  <div>
                    <label>
                      <div>Name for person {i}</div>
                      <input
                        value={subField.state.value}
                        onChange={(e) =>
                          subField.handleChange(e.target.value)
                        }
                      />
                    </label>
                  </div>
                )
              }}
            </form.Field>
          )
        })}
        <button
          onClick={() => field.pushValue({ name: '', age: 0 })}
          type="button"
        >
          Add person
        </button>
      </div>
    )
  }}
</form.Field>


I want to render my own component for the array field, but I cannot figure out how to get access to <form.Field> from my child component.

I tried this:

const form = useFormContext();

<form.Field name="myArrayFieldName">


But I get the following typescript error on the name prop: Type 'string' is not assignable to type 'never'.

I've tried a few other things to try get this working and I'm kinda stuck now. I searched github issues and this discord but still have not found a definitive answer...

Is there a straightforward way to render <form.Field> from inside child components?
Was this page helpful?