Created
June 23, 2018 21:43
-
-
Save reccanti/c61f486335163b588d39edd32bff8197 to your computer and use it in GitHub Desktop.
ReasonReact refs in stateless component
This file contains 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
let component = ReasonReact.statelessComponent("MyComponent"); | |
/** | |
* This will be used to hold a ref to our input element | |
*/ | |
let inputRef: ref(option('a)) = ref(None); | |
/** | |
* sets the ref to the input element | |
*/ | |
let setInputRef = theRef => inputRef := Js.Nullable.toOption(theRef); | |
/** | |
* Extracts a value from a DOM element and calls a provided function | |
*/ | |
let handleSubmit = (_e, onSubmit) => | |
switch (inputRef^) { | |
| Some((element: Dom.element)) => | |
onSubmit(ReactDOMRe.domElementToObj(element)##value) | |
| _ => () | |
}; | |
let make = (~onSubmit, _children) => { | |
...component, | |
render: _self => | |
<div> | |
<input ref=setInputRef _type="text" name="myinput" /> | |
<button onClick=(_e => handleSubmit(_e, onSubmit))> | |
(ReasonReact.string("Submit")) | |
</button> | |
</div>, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment