Skip to content

Instantly share code, notes, and snippets.

@reccanti
Created June 23, 2018 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reccanti/c61f486335163b588d39edd32bff8197 to your computer and use it in GitHub Desktop.
Save reccanti/c61f486335163b588d39edd32bff8197 to your computer and use it in GitHub Desktop.
ReasonReact refs in stateless component
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