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);
The onkeypress event occurs when the user presses a key (on the keyboard). Tip: The order of events related to the onkeypress event: onkeydown. onkeypress. onkeyup.
Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input.
The onkeypress attribute fires when the user presses a key (on the keyboard).
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>
);
}
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