I have a Material UI Autocomplete form in a React component. It works perfect, except the ENTER key is currently clearing the input field. I simply want the input field to not be cleared when the user hits ENTER key. I searched through all the similar questions on Stackoverflow, and none of them deal with ignoring this key inside of an Autocomplete form (they mostly deal with regular input forms). Below I list all the things I have tried that don't work.
How can I disable the ENTER key in this situation??
I have tried ignoring the enter key such as :
onKeyPress={(event) => {return event.key !== 'Enter';}}
I have also tried stopping the autocomplete enter key from being taken as a form submit (hoping it wouldn't clear the form) by doing this:
onKeyPress={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
return false;
}
}
I even tried :
onKeyPress={(event) => {
if (event.key === 'Enter') {
event.stopPropagation();
return false;
}
}
And, yes, I also tried using onKeyDown
instead onKeyPress
for both the above examples.
Finally, I tried using the disableClearable
option in the Autocomplete component as below:
const onInputChange = useCallback(
(_event: ChangeEvent<{}>, newInputValue: string) => {
debounceFetchData(newInputValue);
},
[debounceFetchData]
);
return (
<section className={classes.container}>
<SearchIcon className={classes.icon} />
<Autocomplete
id="search"
options={options}
disableClearable
getOptionLabel={() => ''}
filterOptions={(x) => x}
fullWidth
freeSolo
onInputChange={onInputChange}
renderInput={(params) => (
<TextField
{...params}
placeholder="Search"
variant="outlined"
size="small"
inputProps={{
...params.inputProps,
'aria-label': 'Search',
}}
/>
)}
...
...
...
/>