Тарас Лукавий Тарас Лукавий - 3 months ago 47
React JSX Question

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?

Answer

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());
});