Home > other >  How do I return the value of the key pressed in React
How do I return the value of the key pressed in React

Time:03-22

I am very new to react - trying to build a fairly simple app. What I would like to do is just get and console.log the value of the key pressed by the user (eg. if user presses k then k appears in console.log).

This is what I have so far:

import "./TextArea.css";

const TextArea = () => {
  const registerKeyPresses = (e) => {
    console.log(e);
  };

  return (
    <form className="textinputframe">
      <div className="textinputframe">
        <textarea
          className="textinput"
          type="text"
          onKeyDown={registerKeyPresses}
        />
      </div>
    </form>
  );
};

export default TextArea;

And this is what it returns:

SyntheticBaseEvent {_reactName: 'onKeyDown', _targetInst: null, type: 'keydown', nativeEvent: KeyboardEvent, target: textarea.textinput, …}
altKey: false
bubbles: true
cancelable: true
charCode: 0
code: "MetaLeft"
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 0
eventPhase: 3
getModifierState: ƒ modifierStateGetter(keyArg)
isDefaultPrevented: ƒ functionThatReturnsFalse()
isPropagationStopped: ƒ functionThatReturnsFalse()
isTrusted: true
key: "Meta"
keyCode: 91
locale: undefined
location: 1
metaKey: true
nativeEvent: KeyboardEvent {isTrusted: true, key: 'Meta', code: 'MetaLeft', location: 1, ctrlKey: false, …}
repeat: false
shiftKey: false
target: textarea.textinput
timeStamp: 9066952.4
type: "keydown"
view: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
which: 91
_reactName: "onKeyDown"
_targetInst: null
[[Prototype]]: Object

CodePudding user response:

Here's the keydown event documentation. From there you'll see that

  1. keydown events are all also KeyboadEvents
    and
  2. All KeyboardEvents have a .code property that corresponds to the physical key pressed on the keyboard that produced the event (e.g. MetaLeft in your example)

Now you could console log the physical key if that's useful for you, or — if you're looking for only the output of the keypress, there's a .key property in KeyboardEvents you can use instead.

The difference in .code and .key in a nutshell is that if you press e.g. the 'k' key on your keyboard, .code will equal "KeyK" and .key will equal "k".

If you instead want the value of the textarea you can use Event.target (since keydown is a KeyboardEvent which is an Event), which corresponds to the textfield element. The element will have a .value prop that will equal the value of the textfield.

  • Related