How to attach ref to a dom node with useRef hook

reasonreact

#1

Hi there. How do I use the new useRef hook to attach a ref to a DOM node? this github issue is the only example I found so far, but it fails when I try to pass my ref to a div because the types don’t match and I get this error:

Error: This expression has type
       React.Ref.t(Js.Nullable.t(ref(option(Dom.element))))
       but an expression was expected of type ReactDOMRe.domRef

and I am not sure what I need to pass that would be of type ReactDOMRe.domRef. Any help is appreciated :smiley:
GitHub
Refs in reason-react-native · Issue #419 · reasonml-community/bs…
Bringing this over from Discord as requested by @MoOx. I'm basically not sure if this is the right way to use refs and if the external I've defined in the following example should b…


#2

I had the same problem and actually posted in a previous thread (React Hooks support in ReasonReact) but found the solution on discord :

[@react.component]
let make = (~foo: t) => {

    let myRef = React.useRef(Js.Nullable.null);

    React.useEffect0(() => {
      myRef -> React.Ref.current
            -> Js.Nullable.toOption
            -> Option.map(myRef => /* use myRef of type Dom.element */)
            ->ignore;
      None;
    });

    <div ref={myRef -> ReactDOMRe.Ref.domRef}></div>
};

#3

Yes, that works perfectly, thanks a lot, @tsnobip!
This ref={myRef -> ReactDOMRe.Ref.domRef} was definitely something I would have never come up with. What does it do anyway? I was trying to read the source code but couldn’t find anything that would give me domRef from React.Ref:

module Ref = {
  type t = domRef;
  type currentDomRef = React.Ref.t(Js.nullable(Dom.element));
  type callbackDomRef = Js.nullable(Dom.element) => unit;

  external domRef: currentDomRef => domRef = "%identity";
  external callbackDomRef: callbackDomRef => domRef = "%identity";
};

Is it clear from this source code that you can convert React.ref to ReactDOMRe.domRef and I just can’t see it? Really want to understand how all this hang together :slight_smile:

But your answer should definitely end up in the reason docs :slight_smile:


#4

Yes, my original post was to ask documentation about that, there should definitely be more docs about hooks in reason react.
Regarding your question, an external using the string “%identity” is what is called an identity external in bucklescript, I don’t know how it works under the hood and I’d be curious to know more about it but it acts like a cast from one type to another.


#5

well, they heard us and added a page in the doc :