Middle
How closely have you worked with Ant Design? Have you encountered complex forms? There is an interesting case: a Select, depending on the chosen value, input fields are added or changed. How would you implement this?
sobes.tech AI
Answer from AI
In Ant Design, to implement dynamic forms where the set of input fields depends on the selected value in a Select, you can use component state and conditional rendering.
Example approach:
import React, { useState } from 'react';
import { Form, Select, Input } from 'antd';
const { Option } = Select;
const DynamicForm = () => {
const [selected, setSelected] = useState(null);
const onSelectChange = value => {
setSelected(value);
};
return (
<Form>
<Form.Item label="Choose an option" name="option">
<Select onChange={onSelectChange} placeholder="Select">
<Option value="a">Option A</Option>
<Option value="b">Option B</Option>
</Select>
</Form.Item>
{selected === 'a' && (
<Form.Item label="Field for A" name="fieldA">
<Input />
</Form.Item>
)}
{selected === 'b' && (
<>
<Form.Item label="Field for B1" name="fieldB1">
<Input />
</Form.Item>
<Form.Item label="Field for B2" name="fieldB2">
<Input />
</Form.Item>
</>
)}
</Form>
);
};
export default DynamicForm;
Thus, when the Select value changes, the state updates, and the form dynamically displays the necessary fields. For more complex scenarios, you can use Form.List for dynamically adding fields or manage the form through Form.useForm.