@ahrefs/bs-react-context

Bucklescript bindings for React Context API

Usage no npm install needed!

<script type="module">
  import ahrefsBsReactContext from 'https://cdn.skypack.dev/@ahrefs/bs-react-context';
</script>

README

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>,
};