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={_ => { // Need Rescript version of this
  }}>{"Click Me"->React.string}</button>

I think this would work:

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


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.


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