I am using Material UI for my React project and unable to detect when the enter key has been pressed. I have tried the following which I thought should work but still unable to detect the event, not sure what I am missing.
I have a custom MUI component
const [search, setSearch] = useState('');
const handleChange = (event) => {
setSearch(event.target.value);
if (event.keyCode == 13) {
console.log('enter key was pressed');
}
}
<SearchBox
value={search}
onChange={handleChange}
placeholder="enter your search here"
}}
/>
I am using Material UI for my React project and unable to detect when the enter key has been pressed. I have tried the following which I thought should work but still unable to detect the event, not sure what I am missing.
I have a custom MUI component
const [search, setSearch] = useState('');
const handleChange = (event) => {
setSearch(event.target.value);
if (event.keyCode == 13) {
console.log('enter key was pressed');
}
}
<SearchBox
value={search}
onChange={handleChange}
placeholder="enter your search here"
}}
/>
Share
Improve this question
asked Nov 16, 2020 at 10:01
p_wavesp_waves
4013 gold badges8 silver badges15 bronze badges
2
|
3 Answers
Reset to default 7keyCode
and charCode
are Deprecated.
instead use the key
method to detect the Enter
key.
onKeyPress={(event) => {
if (event.key === 'Enter')
console.log('Enter Pressed')
}}
According to Material UI Docs, onChange event callback is only invoked if the field value is changed
Try using onKeyPress or onKeyUp, onKeyDown events as per use case
onKeyPress={(event) => {
if (event.keyCode === '13'){
console.log('enter key was pressed');
}}
onkeypress
event is also deprecated.
I choose to use onKeyDown
instead of, like this:
onKeyDown={(event) => {
if (event.key === 'Enter')
console.log('Enter Pressed')
}
reference: https://www.w3schools.com/jsref/event_onkeypress.asp
onKeyDown
- stackoverflow.com/questions/43384039/… – Sarun UK Commented Nov 16, 2020 at 10:07