ml-in-barcelona / jsoo-react

js_of_ocaml bindings for ReactJS. Based on ReasonReact.
https://ml-in-barcelona.github.io/jsoo-react
MIT License
138 stars 19 forks source link

Add module Context #12

Closed jchavarri closed 3 years ago

jchavarri commented 5 years ago

https://github.com/jchavarri/rroo/blob/7f5e9626742c9b2d8c602fb92c26544c7174d36e/lib/React.re#L43-L55

This is the way it works currently in ReasonReact:

👈 OpenRaw ReasonReact ```reason type context = Foo | Bar; let context = React.createContext(Foo); module ContextProvider = { let make = context->React.Context.provider; [@bs.obj] external makeProps: ( ~value: context, ~children: React.element, ~key: string=?, unit, ) => { . "value": context, "children": React.element, } = ""; }; module Container = { [@react.component] let make = (~children) => { children ; }; }; module Component = { [@react.component] let make = (~children) => { let ctx = React.useContext(context);
// using value here...
; }; }; ```

which can be simplified in:

👈 Open Abstracted ReasonReact ```reason // ReactContext.re module type Config = { type context; let defaultValue: context; }; module Make = (Config: Config) => { let x = React.createContext(Config.defaultValue); module Provider = { let make = x->React.Context.provider; [@bs.obj] external makeProps: ( ~value: Config.context, ~children: React.element, ~key: string=?, unit ) => { . "value": Config.context, "children": React.element, } = ""; }; }; ``` Usage: ```reason module Context = { type t = ...; include ReactContext.Make({ type context = t; let defaultValue = ...; }); }; // Provider children // Consumer let ctx = React.useContext(Context.x); ```

We could start providing an API similar to the first one, at least in a first stage, and without the need to deal with JS object {value, children} of the props or bs.obj and decide after that based on what's possible.

jchavarri commented 3 years ago

Done in https://github.com/jchavarri/jsoo-react/commit/38fd13841865394d628cbfb5e65e09dcbfdd3615.