@ahrefs/bs-react-context

0.1.1 • Public • Published

bs-react-context

This is Bucklescript bindings for React Context API.

Install, npm

yarn add @ahrefs/bs-react-context

Setup

Add bs-react-context to bs-depenencies in your bsconfig.json!

{
  /* ... */
  "bs-dependencies": [
    "@ahrefs/bs-react-context"
  ],
  /* ... */
}

Usage Example

/* ThemeContext.re */
/* Define context */

type theme =
  | Light
  | Dark;

type action =
  | ToggleTheme;

type state = {theme};

type value = {
  dispatch: action => unit,
  state,
};

let initialState = () => {theme: Light};

module ThemeContext =
  Context.MakeContext({
    type t = value;
    let defaultValue = {
      dispatch: _action => Js.log("State has not mounted yet"),
      state: initialState(),
    };
  });

let component = ReasonReact.reducerComponent(__MODULE__);

let make = children => {
  ...component,
  initialState,
  reducer: (action, state) =>
    switch (action) {
    | ToggleTheme =>
      ReasonReact.Update({theme: state.theme == Light ? Dark : Light})
    },
  render: ({state, send}) =>
    ReasonReact.element(
      ThemeContext.Provider.make(~value={state, dispatch: send}, children),
    ),
};

module Consumer = ThemeContext.Consumer;
/* App.re */
/* Provide defined context to your app */

let component = ReasonReact.statelessComponent(__MODULE__);

let make = _children => {
  ...component,
  render: _self => <ThemeContext> <Component /> </ThemeContext>,
};
/* Component.re */
/* Use provided context */

let s = ReasonReact.string;
let component = ReasonReact.statelessComponent(__MODULE__);

let make = _children => {
  ...component,
  render: _self =>
    <ThemeContext.Consumer>
      {({state, dispatch}) =>
         <>
           {switch (state.theme) {
            | Light => "Light theme"->s
            | Dark => "Dark theme"->s
            }}
           <button onClick={_ => dispatch(ToggleTheme)}>
             "Toggle theme"->s
           </button>
         </>}
    </ThemeContext.Consumer>,
};

Package Sidebar

Install

npm i @ahrefs/bs-react-context

Weekly Downloads

2

Version

0.1.1

License

MIT

Unpacked Size

403 kB

Total Files

17

Last publish

Collaborators

  • feihong
  • jchavarri
  • zindel
  • denstr
  • bryanthomaschen
  • khady
  • rustykey
  • germes