Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add onKeyPress event to react material-ui textfield?

Tags:

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}
/>
like image 920
Akhil Kumar Pilli Avatar asked Sep 01 '17 04:09

Akhil Kumar Pilli


People also ask

How do you detect if Enter key is pressed in a text input field using React?

To detect when the user pressed the Enter key when typing in an input field: Add the onKeyDown prop to the input element. Every time the user presses a key in the input field, check if the pressed key is Enter.

How do you show error in TextField in material UI?

To invalidate a TextField in React Material UI, we set the error and helperText props of the TextField to display the error message we want. We set the error prop to make the TextField 's border red when we enter invalid input. And we set the helperText prop to display the error text at the bottom.

How do I change the value of TextField material UI?

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value. And we set the onChange prop to a function that sets the state to a the value that's inputted. We call the useState hook to create the value state and the setValue function to set the value state's value.


2 Answers

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
            }
    }}
like image 127
Peter Avatar answered Sep 21 '22 02:09

Peter


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}
/>
like image 37
m0ncld Avatar answered Sep 18 '22 02:09

m0ncld