How to get Input Value in Rescript?

How to get Input Value in Rescript? as we change the way of accessing object ##, I have no ide how to get the value out of element?

Though this may general question of how accessing object, because in rescript I think like we must do Rescript’s way, otherwise, the compiler will log error.

 The record field value can't be found.
  
  If it's defined in another module or file, bring it into scope by:
  - Prefixing it with said module name: TheModule.value
  - Or specifying its type: let theValue: TheModule.theType = {value: VALUE}

object access syntax in rescript is

let value = obj["key"];

simple input example with react:

@react.component
let make = () => {
  let (text, setText) = React.useState(() => "")

  let handleInputChange = event => {
    let value = ReactEvent.Form.currentTarget(event)["value"]

    setText(_ => value)
  }

  <input type_="text" value={text} onChange={handleInputChange} />
}

4 Likes

You can paste any ReasonML syntax snippet and get its equivalent ReScript syntax in the ReScript playground. Go to the ‘Settings’ tab and flip the syntax from RES to RE and back to RES after pasting the snippet. It will auto-convert.

1 Like

Hello, is there no better way to do this in 2024?
ReactEvent.Form.currentTarget(ev)["value2"] also is valid code and is clearly wrong.

At few points, such “leap of faith” access is the best compromise to compensate for the super-dynamic nature of DOM and event handling.

Extracting the input value from an event is one such point.

I use the following helpers in order to minimise typos:

let getEventValue = e => {
  let target = e->JsxEvent.Form.target
  (target["value"]: string)
}

let getEventChecked = e => {
  let target = e->JsxEvent.Form.target
  (target["checked"]: bool)
}

Hi @bhoot, thanks for posting these helpers.
Would it not make sense to add these to the React binding package?