Search code examples
reactjsreact-final-formreact-final-form-arrays

How to set an initial/default value for the array used by <FieldArray/>?


I have been creating a form with react-final form. This form has some conditional fields, that only display when a user clicks a checkbox. If the checkbox is checked, then a component is rendered.

It is very similar to the example they provide in the documentation, which you can see here. https://codesandbox.io/s/kx8qv67nk5

I am basing myself off that example, and i can add to the field array with a button that calls the push method, exactly as in the example.

What i would like to do is not have to push a button in order to push that object into the array, but rather have the array default already include one object inside.

in other words,

In the example provided, the array starts empty and you push() into the array,the fields that are defined within

How can i have it default to already having one object by default instead of manually pushing it?

Im not sure where that array is getting defined or initialized.


Solution

  • Loick M is close, but for an array, you'd need:

    <Form
      onSubmit={myOnSubmit}
      initialValues={{ musicians: [ { firstName: 'Bob', lastName: 'Marley' } ] }}>
      ...
    </Form>