Search code examples
keyboard-eventssolid-js

Solid.js textarea: detect key or access native keyboard event


Consider this snippet (playground):

<textarea onInput={event => {
  console.log(event.key) // TypeScript error and undefined at runtime
  setState(event.currentTarget.value)
}} />

I want to detect whether the user pressed enter or shift-enter.

The browser native event has key and shiftKey properties, which are absent on Solid's event. Neither can I find an equivalent to React's event.nativeEvent property.

Do I really need to use useKeyDownEvent? That approach seems to suffer from a race condition when using it inside the textarea's onInput though...


Solution

  • The input event fires when the value of an <input><select>, or <textarea> element has been changed.

    Solid does not overwrite events, so your statement about event object with missing properties is not accurate. You should use keydown or keyup event:

    The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events.

    https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event

    There is no race condition but browsers observe specific order when firing events. Events related to keypress comes before changing the value, on input comes after.