Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  135] [ 1]  / answers: 1 / hits: 5465  / 3 Years ago, thu, august 26, 2021, 12:00:00

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',
}}
/>
)}
...
...
...
/>

More From » reactjs

 Answers
12

I had stuck on this for some time as well and found the answer on here.


Simply it can be handled by passing onKeyDown handler to inputProps of <TextField> :


 <Autocomplete
...
renderInput={(params) => (
<TextField
{...params}
...
inputProps={{
...params.inputProps,
onKeyDown: (e) => {
if (e.key === 'Enter') {
e.stopPropagation();
}
},
}}
/>
)}
...
...
...
/>

[#959] Monday, August 16, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;