1

Despite following this stackoverflow thread, I am unable to efficiently detect double shift key press event in my reactjs application.

I added,

componentDidMount() {
    document.addEventListener('keydown', this.handleKeyPress);
}

componentWillUnmount(){
    document.removeEventListener("keydown", this.handleKeyPress);
}

handleKeyPress = (event) => {
    how to detect double shift key press, more efficiently?
}

bijayshrestha
  • 149
  • 1
  • 14

1 Answers1

1

Because with React you have some limitation to use click & double-click events on the same element, I would do it at my own like this:

Create 3 Variables : One for the counter (how often the shift was pressed), and One for elapsed time between the Keypress. State-Variable which notice that Shift was double-pressed

If Key-Event was triggered (BTW: I would use keyup), then you:

  • check if Shift-Key was pressed (check by keycode)
  • (if yes) increment the counter-variable to 1
    • and set the elapsed-time variable to current timestamp.

If additional Key-Events are triggered also check if shift-key's are pressed. If yes, check if the current-timestamp minus elapsed-timestamp is in the range of time you've set to notice a double-keypress (e.g. 1 second). If yes, set your double-press variable to 1, if not, clear the counter and elapsed-time variable.

Hope this gives you an Idea how to handle that. At the page I posted in the first line, there are also a tiny example of kind like this Idea: https://stackoverflow.com/a/40449854/1256697

suther
  • 12,600
  • 4
  • 62
  • 99