Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onKeyDown/onKeyUp events on non-input elements

I need to capture cmd button up and down events, in order to choose, whether to use concatenation or not in setState. How do i get these events, for example, on table element?

like image 598
Taras Lukavyi Avatar asked Aug 25 '16 02:08

Taras Lukavyi


People also ask

What is the difference between onKeyUp and Onkeydown?

The onKeyDown event is triggered when the user presses a key. The onKeyUp event is triggered when the user releases a key.

How do I capture keyboard events in React?

The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers. To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.

What is the event for Onkeydown?

The onkeydown event occurs when the user is pressing a key (on the keyboard). Tip: The order of events related to the onkeydown event: onkeydown. onkeypress.


1 Answers

You have to capture the keypress then in body/window level. Table element doesn't have input focus so you can't capture the keys from table (without input element).

var cmdDown = false;

document.body.addEventListener('keydown', function(event) {
  var key = event.keyCode || event.charCode || 0;
  if ([91,93,224,17].indexOf(key) !== -1) {
    cmdDown = true;
  }
  console.log('CMD DOWN: ' + cmdDown.toString());    
});

document.body.addEventListener('keyup', function(event) {
  var key = event.keyCode || event.charCode || 0;
  if ([91,93,224,17].indexOf(key) !== -1) {
    cmdDown = false;
  }
  console.log('CMD DOWN: ' + cmdDown.toString());
});
like image 69
Hardy Avatar answered Nov 03 '22 09:11

Hardy