How to handle the `onKeyPress` event in ReactJS?
JavascriptReactjsKeypressOnkeypressJavascript Problem Overview
How can I make the onKeyPress
event work in ReactJS? It should alert when enter (keyCode=13)
is pressed.
var Test = React.createClass({
add: function(event){
if(event.keyCode == 13){
alert('Adding....');
}
},
render: function(){
return(
<div>
<input type="text" id="one" onKeyPress={this.add} />
</div>
);
}
});
React.render(<Test />, document.body);
Javascript Solutions
Solution 1 - Javascript
I am working with React 0.14.7, use onKeyPress
and event.key
works well.
handleKeyPress = (event) => {
if(event.key === 'Enter'){
console.log('enter press here! ')
}
}
render: function(){
return(
<div>
<input type="text" id="one" onKeyPress={this.handleKeyPress} />
</div>
);
}
Solution 2 - Javascript
For me onKeyPress
the e.keyCode
is always 0
, but e.charCode
has correct value. If used onKeyDown
the correct code in e.charCode
.
var Title = React.createClass({
handleTest: function(e) {
if (e.charCode == 13) {
alert('Enter... (KeyPress, use charCode)');
}
if (e.keyCode == 13) {
alert('Enter... (KeyDown, use keyCode)');
}
},
render: function() {
return(
<div>
<textarea onKeyPress={this.handleTest} />
</div>
);
}
});
Solution 3 - Javascript
render: function(){
return(
<div>
<input type="text" id="one" onKeyDown={this.add} />
</div>
);
}
onKeyDown
detects keyCode
events.
Solution 4 - Javascript
Keypress event is deprecated, You should use Keydown event instead.
https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event
handleKeyDown(event) {
if(event.keyCode === 13) {
console.log('Enter key pressed')
}
}
render() {
return <input type="text" onKeyDown={this.handleKeyDown} />
}
Solution 5 - Javascript
If you wanted to pass a dynamic param through to a function, inside a dynamic input::
<Input
onKeyPress={(event) => {
if (event.key === "Enter") {
this.doSearch(data.searchParam)
}
}}
placeholder={data.placeholderText} />
/>
Hope this helps someone. :)
Solution 6 - Javascript
var Test = React.createClass({
add: function(event){
if(event.key === 'Enter'){
alert('Adding....');
}
},
render: function(){
return(
<div>
<input type="text" id="one" onKeyPress={(event) => this.add(event)}/>
</div>
);
}
});
Solution 7 - Javascript
React is not passing you the kind of events you might think. Rather, it is passing synthetic events.
In a brief test, event.keyCode == 0
is always true. What you want is event.charCode
Solution 8 - Javascript
Late to the party, but I was trying to get this done in TypeScript and came up with this:
<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}
This prints the exact key pressed to the screen. So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").
Solution 9 - Javascript
This worked for me using hooks, by accessing the window element
useEffect(() => {
window.addEventListener('keypress', e => {
console.log(e.key)
});
}, []);
Solution 10 - Javascript
There are some challenges when it comes to keypress event. Jan Wolter's article on key events is a bit old but explains well why key event detection can be hard.
A few things to note:
keyCode
,which
,charCode
have different value/meaning in keypress from keyup and keydown. They are all deprecated, however supported in major browsers.- Operating system, physical keyboards, browsers(versions) could all have impact on key code/values.
key
andcode
are the recent standard. However, they are not well supported by browsers at the time of writing.
To tackle keyboard events in react apps, I implemented react-keyboard-event-handler. Please have a look.
Solution 11 - Javascript
You need to call event.persist(); this method on your keyPress event. Example:
const MyComponent = (props) => {
const keyboardEvents = (event) =>{
event.persist();
console.log(event.key); // this will return string of key name like 'Enter'
}
return(
<div onKeyPress={keyboardEvents}></div>
)
}
If you now type console.log(event)
in keyboardEvents
function you will get other attributes like:
keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean
And many other attributes
Thanks & Regards
P.S: React Version : 16.13.1
Solution 12 - Javascript
Keyboard Events In React With your generic knowledge of events in React so far, you can now implement keyboard events in React. As mentioned earlier, there are two keyboard events that can be used, the keyup and keydown events.
import React from 'react';
function Quiz(){
handleAnswerChange(event){
if(event.key === 'y'){
alert('The sky is your starting point!')
}
else if (event.key === 'n') {
alert('The sky is your limit👀')
}
}
return (
<div>
<p> Are You Smart?</p>
<input type="text" value={answer} onKeyPress={handleAnswerChange}/>
<small> Press Y for Yes or N for No</small>
</div>
)
}