React useRef input click()

I am looking for a way to fire an artificial click() event on a input using React refs.

  let inputRef = React.useRef(Js.Nullable.null)

  <input ref={ReactDOM.Ref.domRef(divRef)} />

  <button onClick={_ => {
    inputRef.current.click() // Need Rescript version of this
  }}>{"Click Me"->React.string}</button>

I think this would work:
https://rescript-lang.org/try?code=AIIwzgdGCmB2AmACaAPALtATrAhgG0QGM8BLQgawFE9oBbONALkQBEB7WiaG+2NRALwA+RAFdYJfgMQAiYmXIyAUEpr8SsAA6i0AJWgAzQYn05CaCKJj6DACgBSkAHKi8eHCBoRYrvAEoVAB4NbX5MQwEAb1NzFgB5AFkIGwh4DhtbEJ0bPwBfRAB6ISCQHTQ2WCVERAqAYVIKKIB9aAA3KRFIqurEMAB3SUIAC0QsvUMIQlFMcL4AWiFHCBc3Dy9yuM00EgrELp7EAB9EJwroQRFbAIPjgGUOaFtuPwvkPAX5Cmo6Bm7q3O6uVyxWqkRk9QUiAS0BkCxiFjAaEwGgA5gDAgVSmhyrBikA

I don’t know if this is the best way to do it though :slightly_smiling_face:

2 Likes

The question was basically “how do I call click on a Dom ref”. Your solution answers this question pretty straight on.

Here a prose text explanation to get the thought process across:

A domRef is a Js.Nullable.t(Dom.element), so you’d need to:

  • First create a @send binding for click that acts on a Dom.element (since we don’t ship any builtin functions for interacting with Dom values)
  • In the onClick function, unwrap the Js.Nullable.t so you get access to the Dom.element, and then call the click function with the unwrapped value

Sidenote: I’d probably not call the binding clickElement. It’s usually better to stick with the actual JS name if somewhat possible. @send external click: Dom.element => unit = "click" would be more idiomatic. If you are worried about the loss of context, you can still wrap it in some module namespace if needed.

5 Likes

Thank you guys, this is exactly what I was trying to do. I will let you know if we run into any bumps giving it a go!

Looking forward to having the natural instinct on things like this.

Thanks again!

1 Like