I am working on a React application using Ant Design forms, and I have a form with two fields: framework and group. The group field’s options depend on the selected value in the framework field. I want to reset the group field to null whenever the framework field is changed.
import React, { useEffect, useState } from "react";
import { Form, Modal, Select, Button } from "antd";
const App = ({ item, onClose, onEdit }) => {
const [state, setState] = useState(item || {});
const [form] = Form.useForm();
const frameworkOptions = [
{ value: "framework1", label: "Angular" },
{ value: "framework2", label: "React" },
{ value: "framework3", label: "Vue" },
];
const frameworkGroups = {
framework1: [
{ value: "group1", label: "Group One" },
{ value: "group2", label: "Group Two" },
],
framework2: [
{ value: "group3", label: "Group Three" },
{ value: "group4", label: "Group Four" },
],
framework3: [
{ value: "group5", label: "Group Five" },
{ value: "group6", label: "Group Six" },
],
};
const frameworkGroupsForSelectedFramework =
frameworkGroups[state.framework] || [];
useEffect(() => {
setState(item || {});
}, [item]);
const onCloseClicked = () => {
onClose();
};
const onSaveClicked = () => {
onEdit(state);
onClose();
};
const inputChanges = (changedValues, allValues) => {
if (changedValues.framework) {
form.setFieldValue("group", undefined); // Attempting to reset group field
}
setState((prev) => ({ ...prev, ...allValues }));
};
return (
<Modal
title="Framework and Group"
open={true}
form={form}
destroyOnClose
footer={null}
centered
>
<Form
name="frameworkGroupForm"
layout="vertical"
onFinish={onSaveClicked}
onValuesChange={inputChanges}
initialValues={state}
>
<Form.Item
label="Framework"
name="framework"
rules={[{ required: true, message: "Framework is required." }]}
>
<Select options={frameworkOptions} />
</Form.Item>
<Form.Item label="Group" name="group">
<Select options={frameworkGroupsForSelectedFramework} />
</Form.Item>
<div
style={{ display: "flex", justifyContent: "flex-end", gap: "10px" }}
>
<Button onClick={onCloseClicked}>Close</Button>
<Button type="primary" htmlType="submit">
Save
</Button>
</div>
</Form>
</Modal>
);
};
export default App;
The issue I am facing is that when I change the framework field, the group field does not reset to null or clear its value. The options for group update correctly based on the selected framework, but the previously selected value remains in the group field.
I tried using form.setFieldValue("group", undefined) inside the onValuesChange handler, but it doesn’t seem to work as expected.
form={form}is not a prop ofModal, please pass it toForm, i tried and it worked