@ahrefs/bs-react-context
v0.1.1
Published
Bucklescript bindings for React Context API
Downloads
18
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>,
};