Search code examples
javascriptreactjsantd

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

  • 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.