I have a react code which includes a mui drop down on the left side and one Material UI Autocomplete on the right side. The left drop down has three categories as its values:
dropDownVals = [
{ name: "State", values:[{title:"A", flag:true}, {title:"B", flag:false}]},
{ name: "Country", values=[{title:"C", flag:false}, {title:"E", flag:false}]}
]
I want to show the result of drop down selection in the right autocomplete. I mean if user selects "State" in drop down the autocomplete label is changed to "State" and "A" and "B" is shown under "State" and the same for selection of "Country" in drop down.
I wrote this functionality and it works well. But if I select "State" and select "A" as the selected option for Autocomplete and then change the drop down selected value to "Country" the "A" remains as the selected option of Autocomplete. How can I clear the autocomplete value whenever I change the drop down selection?
The problem is most likely related to the controlled state of your right autocomplete. In controlled component, your value should not be undefined
initially. So, if you store right variable like this:
const [selectedRight, setSelectedRight] = useState();
you should pass it to the autocomplete like:
value={selectedRight || null}
in order to prevent passing undefined value to the autocomplete permanently.
You can take a look at this StackBlitz for a live working example of clearing mui autocomplete value programmatically.