Search code examples
javascriptreactjsuser-interfacecontrolskey-bindings

react js how to prevent arrow keys from switching controls


I am working on react browser-based game where a player can select a unit to place on a battlefield, and then he can use the arrow keys to move the unit around on a map.

The problem is that the list of units is a react radio group, and that pressing the arrow keys also switches the focus from the one radio button to the next, which causes a different unit to be selected by the very same action that was supposed to (and does) move the initial unit, so the whole thing becomes quite confusing.

I use event listeners bound to the componentDidMount method to bind the arrow keys to move the unit.

componentDidMount(){
  ...
  document.addEventListener("keydown", this.handleKeyDown.bind(this));
  document.addEventListener("keyup", this.handleKeyUp.bind(this));

While there may be a number of ways to solve this, I would prefer to simply disable the switching of radio-button using the arrow keys. Does anyone know how to turn that off?

I found this article, but it mostly goes over my head, and besides I am still hoping there is an easier way to do this.


Solution

  • React suggest to use preventDefault statement rather than using return false:

    handleKeyDown = (e) => {
     //... rest of your code
     e.preventDefault()
    }
    

    Also, you don't need to bind addEventListener inside componentDidMount hook. The event will be called from event binding of component.

    Example:

    <YourComponent onKeyDown={this.handleKeyDown} onKeyUp={this.handleKeyUp} />