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}
/>
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.
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.
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.
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}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With