user967451
user967451

Reputation:

What is the right way to type check an event onKeyPress in React?

The following code:

  <input
    type="text"
    onKeyPress={(e) => addTag(e)}
  />

  const addTag = (e: React.SyntheticEvent<HTMLInputElement>): void => {
    if (e.key === 'Enter')) {
      // Do something with `e.currentTarget.value`
    }
  };

It results in this error:

Property 'key' does not exist on type 'SyntheticEvent<HTMLInputElement, Event>'.

How shall I type event here? Whatever I use must also work with e.currentTarget.value.

Upvotes: 1

Views: 368

Answers (1)

Honza
Honza

Reputation: 703

onKeyPress event of React input has this type: (event: React.KeyboardEvent<HTMLInputElement>) => void

Type definition: https://github.com/facebook/react/blob/4cb399a433771c84e861d5ca3d38a24733d23ad8/packages/react-interactions/events/src/dom/Keyboard.js#L36

Upvotes: 1

Related Questions