All Projects → Hehk → Reason React Context

Hehk / Reason React Context

A library to add a context library for reason react

Programming Languages

ocaml
1615 projects

This a an implementation of the new context react context api in pure ReasonML

State

It seems to cover the base api. If there is something missing, please file an issue :D

Install

npm install --save reason-react-context

Example

Creating a context:

type t =
  | Light
  | Dark;

module Context =
  ReasonReactContext.CreateContext(
    {
      type state = t;
      let name = "Theme";
      let defaultValue = Light;
    }
  );

Using the Provider module:

type action =
  | ChangeTheme(Theme.t);

type state = {theme: Theme.t};

let component = ReasonReact.reducerComponent("App");

let make = _children => {
  ...component,
  initialState: () => {theme: Light},
  reducer: (action, _state) =>
    switch action {
    | ChangeTheme(newTheme) => ReasonReact.Update({theme: newTheme})
    },
  render: ({send, state}) =>
    <div className="App">
      <Theme.Context.Provider value=state.theme>
        <Background>
          <button onClick=(_e => send(ChangeTheme(state.theme === Dark ? Light : Dark)))>
            (ReasonReact.stringToElement("Toggle Theme"))
          </button>
          <Title message="Reason Context" />
        </Background>
      </Theme.Context.Provider>
    </div>
};

Using the Consumer module:

let component = ReasonReact.statelessComponent("background");

let make = children => {
  ...component,
  render: _self =>
    <Theme.Context.Consumer>
      ...(
           theme =>
             ReasonReact.createDomElement(
               "div",
               ~props={"className": theme === Light ? "background-light" : "background-dark"},
               children
             )
         )
    </Theme.Context.Consumer>
};

If you want to see more there is a full theme example and a global state example in the /example folder of this repo.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].