p_waves
p_waves

Reputation: 401

Material UI Input not detecting when enter key is pressed

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"
  }}
/>

Upvotes: 7

Views: 10636

Answers (3)

hlx
hlx

Reputation: 61

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

Upvotes: 4

Ericgit
Ericgit

Reputation: 7103

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')
}}

Upvotes: 7

Shashank Garg
Shashank Garg

Reputation: 296

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');      
}}

Upvotes: 6

Related Questions