Skip to content

Instantly share code, notes, and snippets.

@scott-fleischman
Created May 23, 2019 18:10
Show Gist options
  • Save scott-fleischman/f498191260ded53a5699cc4620f8bdee to your computer and use it in GitHub Desktop.
Save scott-fleischman/f498191260ded53a5699cc4620f8bdee to your computer and use it in GitHub Desktop.
ReasonML/React Hooks Measuring DOM Node
[@react.component]
let make = (~measureRef) => {
let (show, setShow) = React.useState(_ => false);
if (!show) {
<button onClick={_ => setShow(_ => true)}>
{ReasonReact.string("Show child")}
</button>;
} else {
<h1 ref={ReactDOMRe.Ref.callbackDomRef(measureRef)}>
{ReasonReact.string("Hello, world")}
</h1>;
};
};
[@bs.send] external getBoundingClientRect: Dom.element => Js.t({..}) = "";
[@react.component]
let make = () => {
let (height, setHeight) = React.useState(_ => 0.0);
let measureRef =
React.useCallback(nodeOption =>
switch (Js.Nullable.toOption(nodeOption)) {
| Some(node) => setHeight(getBoundingClientRect(node)##height)
| None => ()
}
);
<>
<MeasureChild measureRef />
{if (height > 0.0) {
<h2>
{ReasonReact.string(
"The above header is "
++ Js.Float.toFixed(Js.Math.round(height))
++ "px tall",
)}
</h2>;
} else {
ReasonReact.null;
}}
</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment