26

I used a TextField from react material-ui. I want to know whether the user has pressed Ctrl+Enter. I have tried using onKeyPress event but got no result. How can I achieve this?

<TextField
    value={this.state.message}
    autoFocus={true}
    hintText='Type your message here'
    onChange={this.onChangeMessage}
    onKeyPress={(event) => {
        if (event.ctrlKey && event.keyCode == '13')
            this.sendMessage();
    }}
    multiLine={true}
/>
dat3450
  • 954
  • 3
  • 13
  • 27
Akhil Kumar Pilli
  • 259
  • 1
  • 3
  • 4

6 Answers6

30

onKeyPress is a synthetic Key event that React supports as mentioned here. Try this code:

 onKeyPress= {(e) => {
            if (e.key === 'Enter') {
              console.log('Enter key pressed');
              // write your functionality here
            }
    }}
Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
Peter
  • 10,492
  • 21
  • 82
  • 132
12

Maybe you should try onKeyUp instead of onKeyPress

<TextField
    value={this.state.message}
    autoFocus={true}
    hintText='Type your message here'
    onChange={this.onChangeMessage}
    onKeyUp={(event) => {
        if (event.ctrlKey && event.key== 'Enter')
            this.sendMessage();
    }}
    multiLine={true}
/>
m0ncld
  • 301
  • 4
  • 10
9

You'd better use onKeyDown for this purpose. Here's the reason (link):

  • The onKeyDown event is triggered when the user presses a key.
  • The onKeyUp event is triggered when the user releases a key.
  • The onKeyPress event is actually an onKeyDown followed by an onKeyUp.

So, the code will be:

onKeyDown={(e) => {
   if (e.key === "Enter") {
      desiredFunction();
   }
}}
Ali Tourani
  • 1,170
  • 3
  • 21
  • 31
1

With material-ui, and typscript I am using:

              <TextInput
                id="password"
                label="Password"
                type="password"
                onKeyPress={(data: any) => {
                  if (data.charCode === 13) {
                    console.log("Key `Enter` pressed");
                  }
                }}
                value={password}
                onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
                  this.setState({ password: event.target.value })
                }
              />
Alan
  • 9,167
  • 4
  • 52
  • 70
0

You can use this trick:

 <TextField
        value={this.state.message}
        autoFocus={true}
        hintText='Type your message here'
        onChange={this.onChangeMessage}
        onKeyDown={(event) => {
            var evtobj = window.event ? event : e
            if (evtobj.ctrlKey && evtobj.key == 'Enter')
              this.sendMessage()
          }}
        multiLine={true}
    />
MohammadHossein
  • 51
  • 1
  • 3
  • 12
-3

Please update the onKeyPress event with the below code

if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey)

Please see the link for Key Code Values

Mothy
  • 406
  • 1
  • 7
  • 19