1

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?

Roy
  • 1,612
  • 2
  • 12
  • 38
  • Are you attempting to map [backspace] or [delete] key? [delete] is 46. Also, if you log the event `e` what is the `keyCode`? – Davin Tryon May 18 '20 at 09:57
  • I want to detect the backspace – Roy May 18 '20 at 09:57
  • 2
    Is there a reason you're using `onKeyPress`? Because for that event, `keyCode` will always be 0. Have you tried using `onKeyDown`? – JDansercoer May 18 '20 at 09:57
  • It works. Thanks. I don't really know the difference between them – Roy May 18 '20 at 09:59
  • @Roy More info can be found [here](https://github.com/facebook/react/issues/1898#issuecomment-49563013) – JDansercoer May 18 '20 at 09:59
  • Does this answer your question? [JavaScript listener, "keypress" doesn't detect backspace?](https://stackoverflow.com/questions/4843472/javascript-listener-keypress-doesnt-detect-backspace) – isAif May 18 '20 at 10:05

2 Answers2

4

As can be read here, onKeyPress only receives charCode instead of keyCode.

This gives us three possible answers to this issue:

  • Either change the event to onKeyDown
  • Change the listener to check e.charCode
  • Use e.which, which will work for both onKeyPress and onKeyDown.
JDansercoer
  • 447
  • 1
  • 5
  • 16
1

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} />;
  }
joy08
  • 9,004
  • 8
  • 38
  • 73