最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Material UI Input not detecting when enter key is pressed - Stack Overflow

programmeradmin2浏览0评论

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
  • 1 onKeyDown - stackoverflow.com/questions/43384039/… – Sarun UK Commented Nov 16, 2020 at 10:07
  • 1 Thank you, found answer in this thread – p_waves Commented Nov 16, 2020 at 10:23
Add a comment  | 

3 Answers 3

Reset to default 7

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

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

发布评论

评论列表(0)

  1. 暂无评论