In Ant Design 4, Form.List is a component used for handling dynamic form items. If you want to dynamically set values in Form.List using the setFieldsValue method, you need to properly manage the form's data structure to ensure that the data paths match the form field paths.
Step 1: Creating Form and Form.List
First, you need to have a basic structure using Form and Form.List. For example:
jsximport React from 'react'; import { Form, Input, Button } from 'antd'; const DynamicFieldSet = () => { const [form] = Form.useForm(); return ( <Form form={form} name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off"> <Form.List name="users"> {(fields, { add, remove }) => ( fields.map(({ key, name, ...restField }) => ( <Form.Item key={key} {...restField} name={[name, 'first']} rules={[{ required: true, message: 'Missing first name' }]}> <Input placeholder="First Name" /> </Form.Item> )) )} </Form.List> <Button type="primary" onClick={() => add()}>Add User</Button> <Button type="primary" htmlType="submit">Submit</Button> </Form> ); }; export default DynamicFieldSet;
Step 2: Using setFieldsValue
When setting values in Form.List, you must provide the complete path and value. For example, to set the first user's name:
jsxconst setInitialValues = () => { form.setFieldsValue({ users: [ { first: 'John' } ] }); };
Example Illustration
Assume you have a button to trigger the initial value setting function:
jsx<Button type="button" onClick={setInitialValues}>Set John's Name</Button>
This button's click event calls the setInitialValues function, which uses setFieldsValue to set the first user's name to "John".
Important Notes
- Ensure your data structure matches the
nameattribute inForm.Item. - Handle more complex data structures when
Form.Listis nested multiple layers or contains various input types.
By following these steps, you should be able to dynamically set form field values in Ant Design 4's Form.List.