0

This should be extremely easy but apprently not. In a standard HTML input element, I would like to perform and action if Enter is hit. I am trying to learn TS and cannot figure out which type fits everything I need.

<input type="text" onChange={handleInput} />
const handleInput = (event: any) => {
  if (event.key === 'Enter') {
    console.log(event.target.value);
  };
};
  • If event: InputEvent then I can't even call the function, because the event type is wholly incompatible.
  • If event: ChangeEvent<HTMLInputEvent> then I can reach event.target.value, but an error says there is no key property, which is correct. In this case, the keystroke value is kept under event.nativeEvent.data. However, if I go for if (event.nativeEvent.data...) then an error says there is no data property, even though there clearly is:
// from the console
nativeEvent: InputEvent {isTrusted: true, data: "d"...)
  • If event: KeyboardEvent then I get event.key but now event.target.value doesn't exist.

I would love to know two things:

  1. What is the correct type for this event?
  2. Where can I learn about the endless amount of types for these minor differences?
Ronny Efronny
  • 1,148
  • 9
  • 28
  • `event.nativeEvenet` won't work, spelling matters in programming, that's why accessing the `.data` property of it throws a TS error - it's spelled `nativeEvent` – CertainPerformance May 20 '21 at 15:26
  • 1
    To clarify, I use an IDE, so any typos are very obviously me typing here. – Ronny Efronny May 20 '21 at 15:42
  • The second answer of the following thread addresses your situation: [to call onChange event after pressing Enter key](https://stackoverflow.com/a/46896944/1218980) – Emile Bergeron May 20 '21 at 16:17

1 Answers1

1

To listen for a key being pressed down you need onKeyDown, not onChange.

const handleEnter = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "Enter") { ... }
}

<input onKeyDown={handleEnter} ... />
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Upon trying this the error for `event.target.value` says `Property 'value' does not exist on type 'EventTarget'.`. – Ronny Efronny May 20 '21 at 15:45
  • @RonnyEfronny you'll have to keep both events, the `onChange` to update some local state, and the `onKeyDown` which will use that state, not the (invalid) `event.target.value`. – Emile Bergeron May 20 '21 at 16:15
  • 1
    After some fiddling I found that if I change `target` to `currentTarget` in this solution, I have access to the `value`. If you add it to the answer I can mark it. – Ronny Efronny May 20 '21 at 16:43