How to work with "nativeEvent"

I’m trying to access the “code” property on a keyboard event but it isn’t there. I know it is available under the .nativeEvent property but can’t figure out how to use it. If I mouse over that type it shows as {...}. What is that?

    <input
      onKeyDown={k => {
        k->ReactEvent.Keyboard.stopPropagation
        k->ReactEvent.Keyboard.preventDefault
        // k->ReactEvent.Keyboard.nativeEvent -> // 

I tried doing this but it doesn’t compile…

let x: Dom.keyboardEvent = k->ReactEvent.Keyboard.nativeEvent

How do I access the code property of that event?

I figured out one way to do it and it is kind of ugly. Is this the best way? It seems like this would be a place where I could use those types like Dom.keyboardEvent.

module NativeKeyboardEvent = {
  @get external getCode: 'a => string = "code"
}

      onKeyDown={k => {
        k->ReactEvent.Keyboard.stopPropagation
        k->ReactEvent.Keyboard.preventDefault
        let code = k->ReactEvent.Keyboard.nativeEvent->NativeKeyboardEvent.getCode
        Js.Console.log(code)

I think maybe what I’m looking for is some way to “cast” the native event to some other externally defined type, maybe the Dom.keyboardEvent, and then I can write a bunch of functions that work with that type.

I don’t know what type do they call it but I think it is kind of like any type.
Anyway, I think something like this will do:

let code = ReactEvent.Keyboard.nativeEvent(k)["code"]

The {..} is an object type without any clear definition of attributes. When a type like this pops up, you can use it pretty dynamically with the ["..."] accessor. It’s not your typical any though, because the type-checker will still keep track of how you use the object and locks in types as soon as it sees some concrete usage.

Yeah, you can do that, and you were already on the right track:

module NativeKeyboardEvent = {
  type t
  @get external getCode: t => string = "code"

  external toNativeKeyboardEvent: {..} => t = "%identity"
}

let make = () => {
  let onKeyDown = evt => {
    evt->ReactEvent.Keyboard.preventDefault

    let code =
      evt
      ->ReactEvent.Keyboard.nativeEvent
      ->NativeKeyboardEvent.toNativeKeyboardEvent
      ->NativeKeyboardEvent.getCode

    Js.log(code)
  }
  <div onKeyDown />
}

Playground Link

1 Like

Thanks very helpful.