reasonreason-react

How to pattern match on a value of type React.Ref.t(Js.Nullable.t('a))


I'm trying to access the DOM element as a JS object.

let navRef = React.useRef(Js.Nullable.null);
  let width =
    switch (Js.Nullable.toOption(navRef)) {
    | None => 0.0
    | Some(nav) => ReactDOMRe.domElementToObj(nav)##clientWidth
    };

But I have a type eror on navRef inside Js.Nullable.toOption

Error: This expression has type React.Ref.t(Js.Nullable.t('a)) but an expression was expected of type Js.Nullable.t('b) = Js.nullable('b)


Solution

  • React.Ref.t is an opaque type, hence you can't pattern match on it directly. But you can access the value of the ref using React.Ref.current and then pattern match on that:

    let navRef = React.useRef(Js.Nullable.null);
      let width =
        switch (Js.Nullable.toOption(React.Ref.current(navRef))) {
        | None => 0.0
        | Some(nav) => ReactDOMRe.domElementToObj(nav)##clientWidth
        };