When using the Ant Design (Antd) React component library, if you want to pre-fill the first item in a dynamic form, you can leverage Antd's Form and Form.Item components along with the initialValues property to set default values. Here, we provide a simple form example for adding a user's email address, where the first item in dynamically added form items is pre-filled by default.
First, ensure you have correctly installed and imported the Antd library and required components:
javascriptimport React, { useState } from 'react'; import { Form, Input, Button, Space } from 'antd'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
Below are the specific implementation steps:
1. Setting the Form Component
Create a React component and use the Form tag to initialize the form. Use the initialValues property to set default values for form items:
javascriptconst DynamicForm = () => { const [form] = Form.useForm(); return ( <Form form={form} name="dynamic_form" initialValues={{ users: [{ email: '' }] }}> {/* Dynamic form items will be placed here */} </Form> ); };
2. Adding Dynamic Form Items
Use Form.List to handle dynamic form items. This component allows users to dynamically add or remove form items. Inside Form.List, you can render each dynamic form item by mapping the fields. The default values set via initialValues will automatically populate the first item:
javascript<Form.List name="users" initialValue={[{ email: 'example@domain.com' }]} // Default value setting > {(fields, { add, remove }) => ( <> {fields.map(({ key, name, fieldKey, ...restField }) => ( <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline"> <Form.Item {...restField} name={[name, 'email']} fieldKey={[fieldKey, 'email']} rules={[{ required: true, message: 'Please enter an email address' }]}> <Input placeholder="Email address" /> </Form.Item> <MinusCircleOutlined onClick={() => remove(name)} /> </Space> ))} <Form.Item> <Button type="primary" onClick={() => add()} icon={<PlusOutlined />}> Add Email </Button> </Form.Item> </> ))} </Form.List>
3. Finalizing the Component and Testing
Now, you have set up a form item with dynamic add and remove functionality, and the first form item is pre-filled with the preset email address. You can submit the form to verify all input values.
javascript<Form.Item> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item>
Add this component to your application and test it to ensure everything works as expected.
Conclusion
By following these steps, you can set default values for the first item in dynamic forms using Antd. This not only enhances user experience but also reduces input workload, especially when form items are numerous or complex. In enterprise applications, dynamic forms are widely used, and effectively managing the state and data flow of dynamic forms is crucial.