ReasonML translation of code from https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
Created
May 23, 2019 18:10
-
-
Save scott-fleischman/f498191260ded53a5699cc4620f8bdee to your computer and use it in GitHub Desktop.
ReasonML/React Hooks Measuring DOM Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[@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>; | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[@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