6

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"
  }}
/>
p_waves
  • 361
  • 1
  • 6
  • 12

3 Answers3

6

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');      
}}
Shashank Garg
  • 286
  • 2
  • 7
6

keyCode and charCode are Deprecated.

instead use the key method to detect the Enter key.

onKeyPress={(event) => {
  if (event.key === 'Enter')
    console.log('Enter Pressed')
}}
Ericgit
  • 6,089
  • 2
  • 42
  • 53
1

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

hlx
  • 31
  • 4