I’m working on a React form using Ant Design’s Form component. The form includes several dropdowns, including facility
, specialization
, and doctor
. The doctor dropdown should be cleared whenever the facility
or specialization
dropdown values change, and the doctor
dropdown should be repopulated based on the new facility
and specialization
values.
Here’s a summary of the setup:
- I’m using Ant Design’s Form component and useForm hook to manage the
form state. - The doctor dropdown is a custom component called SearchableDropDown
that fetches options based on the selected facility and
specialization. - I want the doctor dropdown to clear its value whenever the facility
or specialization changes.
Issue:
Despite calling form.setFieldsValue({ doctorId: undefined });
and setting setDoctor(null);
in the useEffect
hook, the doctorId
dropdown does not clear its value as expected when facility
or specialization
changes.
Code Example:
you can find the code here on Stack Blitz
What I’ve Tried:
- Setting the doctorId field value to
undefined
ornull
. - Adding a
key
prop to theSearchableDropDown
to force
re-rendering. - Manually setting the
doctor
state tonull
.
Question:
How can I programmatically clear the doctorId
dropdown value when either the facility
or specialization
dropdown changes in an Ant Design form? What is the correct approach to ensure that the doctor
dropdown is cleared and reset based on the new facility
and specialization
selections?
Any advice or suggestions would be greatly appreciated. Thanks in advance!
2
Answers
Add an internal state
internalValue
inside yourSearchableDropDown
to track the passed value.Pass it to the
Select
as valueAnd the value can be set to undefined in case the change of the
queryParams
doctorId
field is not reset is because you didn’t connectform
with Form component. Second there’s no need to store facilityId, specializationId or any form field related field in state since you can get watch fromform.getFieldValue
or Form.useWatch(‘facilityId’) if you watch the value of a field. You can use onChange on facilityId and specializationId to reset doctorId valueform.resetFields(['doctorId])
Here’s the complete code with some improvements
page.tsx
SearchableDropDown.tsx