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

interop
reasonreact

#1

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.


#2

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:
domRef
->React.Ref.current
->Js.Nullable.toOption
->Option.map(el => el->ReactDOMRe.domElementToObj##click())
->ignore;
  1. Type-safe, but requires Webapi package:
Webapi.Dom.(
  domRef
  ->React.Ref.current
  ->Js.Nullable.toOption
  ->Option.flatMap(Element.asHtmlElement)
  ->Option.map(HtmlElement.click)
);

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 ReasonML.chat 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.


#3

I went with

let currentHtmlIter = (ref, ~f) => {
  ref
  ->React.Ref.current
  ->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.