Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically close Material UI Autocomplete popper results

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();
  };
like image 348
sybercoda Avatar asked Apr 18 '26 04:04

sybercoda


1 Answers

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} />}
       /* ... */
       />}
    />
  );
}
like image 192
Oluwafemi Sule Avatar answered Apr 21 '26 10:04

Oluwafemi Sule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!