Reactjs – How to set multiple FormItems under Form.List in antd V4

antdreactjs

Single FormItem Demo in antd:https://ant.design/components/form/#components-form-demo-dynamic-form-item. There only one FormItem generated dynamically everytime.

And, here is What I want to achieve.

But I always got some errors like wrong interaction, wrong validation or wrong form value.

My code:

<Form.List name="passenger">
    {(fields, { add, remove }) => {
      return (
        <div>
          {fields.map((field, index) => (
            <Form.Item
              {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
              label={index === 0 ? 'Passengers' : ''}
              required={false}
              key={field.key}
            >
              <Form.Item
                {...field}
                validateTrigger={['onChange', 'onBlur']}
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: "Please input passenger's name or delete this field.",
                  },
                ]}
                noStyle
              >
                <Input placeholder="passenger name" style={{ width: '40%' }} />
              </Form.Item>

              <Form.Item
                name={['age', index]}
                validateTrigger={['onChange', 'onBlur']}
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: "Please input passenger's age or delete this field.",
                  },
                ]}
                noStyle
              >
                <Input placeholder="passenger age" style={{ width: '40%', marginRight: 8 }} />
              </Form.Item>

              {fields.length > 1 ? (
                <MinusCircleOutlined
                  className="dynamic-delete-button"
                  onClick={() => {
                    remove(field.name);
                  }}
                />
              ) : null}
            </Form.Item>
          ))}
          <Form.Item>
            <Button
              type="dashed"
              onClick={() => {
                add();
              }}
              style={{ width: '60%' }}
            >
              <PlusOutlined /> Add field
            </Button>
          </Form.Item>
        </div>
      );
    }}
  </Form.List>

Best Answer

From the example provided by the antd team given by @Sushilzzz:

The trick is to use field.name in the name props of the Form.Item. You don't have to nest the sub items in another item.

<Form.List name="users">
        {(fields, { add, remove }) => (
            <div>
              {fields.map((field) => (
                    <Form.Item name={[field.name, "name"]}>
                      <Input placeholder="Name" />
                    </Form.Item>
...
Related Topic