'In Mui Autocomplete how to call a function after selecting an option (not simultaneously)

After doing:

  1. Clicking on Autocomplete input
  2. Moving between options by using arrow keys
  3. Selecting an option by pressing enter key

I want to call a function by pressing enter key again but I cannot find out how to do it.

I tried to use onKeyDown event on Autocomplete's input but by selecting a value on pressing enter it calls the function too.



Solution 1:[1]

I found a workaround for this feature I want to implement:

I keep an isOpen state for the Autocomplete and use onClose and onOpen events to change isOpen and on pressing keys in the input I check if the key code is Enter and isOpen is false then I call the method I want:


const [isOpen, setIsOpen] = useState(false);
...

<Autocomplete
      renderInput={(params) => <TextField onKeyDown={(e)=> { 
          if(e.key === 'Enter' && !isOpen) filter()
        } />
      }
      onOpen={()=>setIsOpen(true)}
      onClose={()=>setIsOpen(false)}
    />

Solution 2:[2]

You can use onChange prop in MUI Autocomplete. like:-

<Autocomplete
      disablePortal
      id="combo-box-demo"
      options={[]}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Movie" />}
      onChange={()=>console.log("changed")}
    />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehran Mirshekaran
Solution 2 Shikhar Awasthi