DanMad
DanMad

Reputation: 1755

HandleKeyPress not recognising down arrow

I'm in the process of building a customised, accessible select input with React.js. I need to have the up and down arrow keys function as the tab key would within the scope of select input's options.

I have a handleKeyPress function on the elements that detects when other keys are pressed (for instance 'Enter' works fine).

Here is an example option:

<li
  className="oc-select-field__item"
  tabIndex="0"
  onClick={handleClick}
  onKeyPress={handleKeyPress}
>

...and here is the handleKeyPress function

handleKeyPress = event => {
  if (event.key === 40) {
    console.log('Down arrow key fired'); // does not fire
  }
  if (event.key === 'Enter') {
    console.log('Enter key fired'); // does fire
  }
};

What am I doing wrong that I am not successfully detecting when the down arrow is pressed?

Upvotes: 7

Views: 4694

Answers (2)

wdm
wdm

Reputation: 7189

event.which will give you the numeric value of the key.

event.key and event.code will give you a string value.

Try this tool: http://keycode.info

if (event.key === 'ArrowDown') {
    console.log('Down arrow key fired');
}

As @devserkan mentioned you should use onKeyDown instead of onKeyPress.

The keydown event is fired when a key is pressed down. Unlike the keypress event, the keydown event is fired for keys that produce a character value and for keys that do not produce a character value.

Upvotes: 9

devserkan
devserkan

Reputation: 17618

For Arrow keys, I think you need onKeyDown instead of onKeyPress.

class App extends React.Component {
  handleKeyPress = ( event ) => {
    if ( event.key === "ArrowDown" ) {
      console.log( "Down arrow key fired" ); // does not fire
    }
    if ( event.key === "Enter" ) {
      console.log( "Enter key fired" ); // does fire
    }
  };

  render() {
    return (
      <div>
        <ul>
          <li
            tabIndex="0"
            onClick={this.handleClick}
            onKeyDown={this.handleKeyPress}
          >Foo
          </li>
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 5

Related Questions