Skip to content

Instantly share code, notes, and snippets.

@shinzui
Forked from jaredly/App.re
Created September 8, 2018 15:45
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 shinzui/874157c2f30cd8328bc5e78ee4167ec3 to your computer and use it in GitHub Desktop.
Save shinzui/874157c2f30cd8328bc5e78ee4167ec3 to your computer and use it in GitHub Desktop.
ReasonReact Context API Example
module StringContext =
Context.MakePair({
type t = string;
let defaultValue = "Awesome";
});
let component = ReasonReact.statelessComponent("Tree");
let make = _children => {
...component,
render: _self =>
<StringContext.Provider value="Hello folks">
<div>
<StringContext.Consumer>
...{text => str(text)}
</StringContext.Consumer>
</div>
</StringContext.Provider>,
};
type pair;
[@bs.get] external provider: pair => ReasonReact.reactClass = "Provider";
[@bs.get] external consumer: pair => ReasonReact.reactClass = "Consumer";
[@bs.module "React"] external createContext: 'a => pair = "";
module MakePair = (Config: {
type t;
let defaultValue: t;
}) => {
let _pair = createContext(Config.defaultValue);
module Provider = {
let make = (~value: Config.t, children) =>
ReasonReact.wrapJsForReason(
~reactClass=provider(_pair),
~props={"value": value},
children,
);
};
module Consumer = {
let make = (children: (Config.t) => ReasonReact.reactElement) =>
ReasonReact.wrapJsForReason(
~reactClass=consumer(_pair),
~props=Js.Obj.empty(),
children
)
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment