Reputation: 1922
I have a handleBackspace
function that does something if backspace is being pressed.
I tried this:
const handleBackspace = (e) => {
if(e.keyCode === 8) {
console.log('1')
}
}
//
<input onKeyPress={handleBackspace}>
But that doesn't work. (I tried it with keyCode 13
[enter] and it worked. But keyCode 8
[backspace] doesn't work) Can someone show me a solution?
Upvotes: 1
Views: 2940
Reputation: 517
As can be read here, onKeyPress
only receives charCode
instead of keyCode
.
This gives us three possible answers to this issue:
onKeyDown
e.charCode
e.which
, which will work for both onKeyPress
and onKeyDown
.Upvotes: 4
Reputation: 9652
onKeyDown
detects keyCode
events.
Try changing it to onKeyDown
event.
Sandbox: https://codesandbox.io/s/react-basic-class-component-kzv2k?file=/src/index.js
handleBackspace = e => {
if (e.keyCode === 8) {
console.log("1");
}
};
render() {
return <input onKeyDown={this.handleBackspace} />;
}
Upvotes: 1