Roy
Roy

Reputation: 1922

React onKeyPress event isn't detecting backspace

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

Answers (2)

JDansercoer
JDansercoer

Reputation: 517

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.

Upvotes: 4

joy08
joy08

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

Related Questions