How can I add onKeyPress event to react material-ui textfield?
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 } }}
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}/>
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(); }}}