When using a Mui Autocomplete
with the properties of multiple
and freeSolo
, a situation arises where pressing Return triggers an onChange
event. However, when tabbing out of the Autocomplete widget, the typed text remains without updating the state of the Autocomplete itself (only affecting the state of the TextField
within it).
// This function is called when Return is pressed
function onAddNewItem(e, items) {
console.log("Validation code goes here");
setItems(items);
}
// This function is called for every keystroke in the input field
function onInputChange(e, newItem) {
setInputValue(newItem);
}
return (
<Autocomplete
multiple
freeSolo
disableClearable
options={[]}
value={items}
onChange={onAddNewItem}
inputValue={inputValue}
onInputChange={onInputChange}
renderInput={(params) => (
<TextField {...params} error={error} placeholder="Type here" />
)}
/>
);
For more information, you can also visit this codesandbox link
If you are wondering how to trigger an onChange
event or update the state of the Autocomplete when focusing elsewhere, using onBlur
won't suffice as it does not provide access to the latest 'draft' items from the updated Autocomplete for setting the new state.