Reputation: 565
ReactJS/Material-UI newbie question. I'm making use of Material-UI Autocomplete and am trying to create a function that I can programmatically call to close the Material-UI autocomplete popper results list but struggling on how to do so. So far I've added a ref to the autocomplete field and tried to trigger a blur since the popper already automatically closes onBlur but regrettably I get an error message stating onBlur isn't a function. Any assistance is greatly appreciated.
const closePopper = () => {
myAutocompleteFieldRef.current.onBlur();
};
Upvotes: 3
Views: 7540
Reputation: 565
I was able to accomplish this by making use of the popper "anchorEL"
Upvotes: 0
Reputation: 38962
Switch to implementing AutoComplete element in controlled mode.
You can create state in your component for controlling the open prop of Autocomplete component.
The forward a function which updates the state down to your custom option.
For example,
export default function CustomAutoComplete() {
const [open, setOpen] = useState(false);
const closePopper = () => setOpen(false);
const openPopper = () => setOpen(true);
return (
<Autocomplete
id="controlled-open-sample"
open={open}
onOpen={openPopper}
onClose={closePopper}
renderOption={opt => <CustomLocationOption {...opt} afterSelect={closePopper} />}
/* ... */
/>}
/>
);
}
Upvotes: 8