React 17 adds support for KeyboardEvent.code property to SyntheticEvent

keyCode and charCode that are a part of React SyntheticEvent are inconsistent across platforms and have been deprecated from Web standards for some time now. W3 standard recommends using code and key instead of keyCode and charCode.

React SyntheticEvent already has the key property but the support for the code property was missing. code property is a string that represents the key that was pressed and is very useful when we care about which physical key was pressed, rather than which character it corresponds to.

For example, if we’re developing a game, we might want a certain set of keys (WASD) to move the player in different directions. We want that the mapping should ideally be independent of the keyboard layout (QWERTY, AZERTY), locale, or any modifier keys (Alt, Shift, Ctrl). Pressing the physical key “q” or “Shift + Q” will result in a KeyboardEvent with a code attribute set to “KeyQ”.

Before

With React 16 and earlier, we have to access event.nativeEvent to get the value of the physical key pressed.

export default function App() {
  const handleKeyDown = (event) => {
    const key = event.nativeEvent.code;
    switch (key) {
      case 'KeyW':
        //moveTop();
        break;
      case 'KeyA':
        //moveLeft();
        break;
      case 'KeyS':
        //moveDown();
        break;
      case 'KeyD':
        //moveRight();
        break;
      default:
      //custom logic  
    }
  }
  return (
    <div className="wrapper">
      <div>
        <p>Enter any of the WASD keys to move the player top/left/down/right</p>
        <input onKeyDown={handleKeyDown} />
      </div>
    </div>
  );
}

After

With the changes in React 17, code property is available in synthetic keyboard event.

export default function App() {
  const handleKeyDown = (event) => {
    // We replaced the native event with the synthetic keyboard event
    const key = event.code; 
    switch (key) {
      case 'KeyW':
        //moveTop();
        break;
      case 'KeyA':
        //moveLeft();
        break;
      case 'KeyS':
        //moveDown();
        break;
      case 'KeyD':
        //moveRight();
        break;
      default:
      //custom logic  
    }
  }
  return (
    <div className="wrapper">
      <div>
        <p>Enter any of the WASD keys to move the player top/left/down/right</p>
        <input onKeyDown={handleKeyDown} />
      </div>
    </div>
  );
}

Note:

The values of the code property can be found here for reference.

Need help on your Ruby on Rails or React project?

Join Our Newsletter