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.
After
With the changes in React 17, code
property is
available
in synthetic keyboard event.
Note:
The values of the code
property can be found
here
for reference.