xunux
xunux

Reputation: 1769

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.

Upvotes: 0

Views: 4815

Answers (2)

Erik R.
Erik R.

Reputation: 7272

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

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

Upvotes: 2

Lo&#239;ck M
Lo&#239;ck M

Reputation: 358

You can use "initialValues"

Example :

import { Form } from "react-final-form";
...
myInitData = {
    firstName: "hello",
    lastName: "world"
}
...
render() {
    return 
        <Form
            initialValues={myInitData} 
            onSubmit={this.handleSubmit}
            validate={this.validate}
          >...

Upvotes: 1

Related Questions