'Ant Design reset select

I have 2 <Select>'s. The values in the second are dependant on the selection made on the first. When I change the selected item in the first, the available options on the second update. But if I already have a selection made on the second, that option remains selected even if it isn't supposed to be available based on a change to the first select.

How can I reset the second select to have nothing selected when a change is made to the first select?

First Select:

<FormItem {...formTailLayout}>
    <FormTitle>Operation</FormTitle>
    {getFieldDecorator('Operation', {
    rules: [
        {
        required: true
        }
    ]
    })(
    <Select
        showSearch
        placeholder="Select an option"
        onChange={this.handleOperationChange}
    >
        {operations.map(operation => (
        <Option value={operation.operation_id}>
            {operation.operation_name}
        </Option>
        ))}
    </Select>
    )}
</FormItem>

Second Select:

<FormItem {...formTailLayout}>
    <FormTitle>Metric</FormTitle>
    {getFieldDecorator('Metric', {
    rules: [
        {
        required: true
        }
    ]
    })(
    <Select
        showSearch
        placeholder="Select an operation first"
        onChange={this.handleMetricChange}
    >
        {matrics
        .filter(
            metric => metric.operation_fk === operation_fk
        )
        .map(metric => (
            <Option value={metric.metric_name}>
            {metric.metric_name}
            </Option>
        ))}
    </Select>
    )}
</FormItem>


Solution 1:[1]

You need to take a look at Coordinated Controls example mentioned on ant-design page. You can simply use setFieldsValue in your first onChange method to set the value of second select field.

handleOperationChange = () => {
    this.props.form.setFieldsValue({
        Metric: undefined
    })
}

I have created a sandbox demo.

Solution 2:[2]

In antd, In Class Component, Using Ref, Clear or reset select list value or form item value

  1. add formRef = React.createRef(); just below class component, like:

    export default class TestClass extends Component { formRef = React.createRef(); }

  2. add ref={this.formRef} in <Form /> component like this <Form ref={this.formRef}/>

  3. add this line on btn click or in any function you want

this.formRef.current.setFieldsValue({ network: undefined });

  1. Here network in above step is the name of form item

    <Form.Item name="network" label="Network"></Form.Item>

Solution 3:[3]

Inside handleOperationChange method use resetfileds, this gonna reset your second select box.

this.props.form.resetFields('Metric');

Solution 4:[4]

<Select
    className="mt-3"
    style={{ width: "100%" }}
    placeholder="Select your Sub Category"
    onChange={handleChangeSubCategory}
    disabled={categoryGroup.category === null}
    value={categoryGroup.subcategory || undefined}
 >
    {subCategory.map(item => (
      <Option key={item} value={item} label={item}>
         <div>
            <Avatar style={{ background: "#10899e" }}>
               {item[0]}
            </Avatar>{" "}
                {item}
             </div>
       </Option>
       ))}
</Select>

Solution 5:[5]

If functional component is used, then we can use Form:

const [form] = Form.useForm()

and it is possible to clear value like this:

const someMethodToClearCurrentSelection = () => {
    // ... the code is omitted for the brevity
    form.setFieldsValue({ fooProduct: undefined })
}

and our control looks like this:

<Form form={form} name="basic" onFinish={onFinish} layout="vertical">
<Form.Item
    key="fooProduct"
    name="fooProduct"
    label="Some product"
    className={s.fooContainer}
    rules={[
        {
            required: true,
            message: `Field 'Some produc' is required`,
        },
    ]}
>
    <Select
        showSearch
        optionFilterProp="children"
        filterOption={(input, option) =>
            option?.children.toLowerCase().includes(input.toLowerCase())
        }
        allowClear
        onChange={handleMarkClick}
    >
        {products.map((option) => (
            <Option key={option.id} value={option.id}>
                {option.name}
            </Option>
        ))}
    </Select>
</Form.Item>

Read more in antd docs here and examples while migrating from v3 to v4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Triyugi Narayan Mani
Solution 2 Jefferson
Solution 3 Hemanthvrm
Solution 4 Paulo Spiguel
Solution 5