How Can I Trigger an Event on the Underlying DOM Node of a ReasonReact Ref?



I’m attempting to use the browser’s native file upload functionality, and to do so I need to trigger a click event on a hidden input element.

I have a ref, as described here, but it’s not clear to me how I can execute the click event upon the underlying DOM node.

In theory, this pattern would apply to other DOM node actions like focus and blur.


Thanks to @alexfedoseev in the ReasonML Discord channel:

In JS, click / blur / focus are methods on DOM element object. In Reason, one must use the appropriate functions to call these methods.

There exist 2 ways to achieve it:

  1. Less type-safe, provided by ReasonReact:
-> => el->ReactDOMRe.domElementToObj##click())
  1. Type-safe, but requires Webapi package:

PSA: If you frequent the ReasonML Discord channel and found this helpful, please consider adding answers received via chat (especially those likely to get asked frequently) to the forum. Hopefully this will reduce the load on those providing help in the Discord channel, and make the learning curve a bit shallower for those Googling for help.


I went with

let currentHtmlIter = (ref, ~f) => {
  ->Js.Nullable.iter((. el) => el->Webapi.Dom.Element.unsafeAsHtmlElement->f);

Because people don’t usually check if reference is an html element in vanilla JS: if current is present, then it’s probably points to an html element, unless you’re doing something weird.

But converting to option and using asHtmlElement is probably technically safer.