How to handle the `onKeyPress` event in ReactJS?
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);
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>
);
}
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>
);
}
});
React Keyboard Events.
render: function(){
return(
<div>
<input type="text" id="one" onKeyDown={this.add} />
</div>
);
}
onKeyDown
detects keyCode
events.