Olo
Olo

Reputation: 91

Dynamic Form with initial values

Sorry for my english.

Like in this example

https://codesandbox.io/s/wonderful-lichterman-br63z?file=/index.js

Form.List is rendering the Array of "Fields" which initally is empty.

I would like to put my own array to be rendered from the start.

Expected result

Upvotes: 2

Views: 5356

Answers (2)

alextrastero
alextrastero

Reputation: 4280

The docs are a bit short on explanation for the Form.List, and since a code sample is worth a thousand words...

This renders the dynamic form list with one item already visible:

const initialValues = {
  users: [
    { age: undefined } // undefined will render the placeholder
  ] 
};

<Form initialValues={initialValues}>
  <Form.List name="users">
    {(fields, { add }) => {
      return (
        <div>
          {fields.map(field => (
            <Row key={field.key}>
              <Col>
                <Form.Item
                  placeholder="age"
                  name={[field.age, 'age']}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  placeholder="sex"
                  name={[field.sex, 'sex']}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  placeholder="name"
                  name={[field.name, 'name']}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          ))}
          <button onClick={() => add()}>Add</button>
        </div> 
      )
    }}
  </Form.List>
</Form>

Upvotes: 3

Anuj Shah
Anuj Shah

Reputation: 571

you can do it using initialValues prop of Form.

Working example: https://codesandbox.io/s/bold-turing-g8ft6?file=/index.js
Docs: https://ant.design/components/form/#API

Upvotes: 2

Related Questions