ReasonReact Context with HOC

mxdavis
Astrolabe Diagnostics

--

My users each have a library of experiments they can browse through. When they examine a specific experiment, some basic information, such as the experiment name, needs to be accessible to various components. It did not make sense to pass the experiment’s name around as props through each component, and redux felt a little overkill for just a small string. I decided to try out React Context.

To make things a little more complex, I wanted to pass in just the experiment’s name, and have access through the context to the name and a sanitized version of the name. To achieve this, I needed to wrap React Context in a HOC.

First I was playing with this concept on sandbox (with Colin Key) and we came up with:

When setting the experiment name, we called ExperimentContextProvider with the props of name, and that called the React Context with a sanitizedName and the original name, which thereby made both available through ExperimentContext.

All works, now make this ReasonReact. Eaaasy, right?

I’ve got this! I just need to convert line by line from JS to ReasonML:

All is good until I hit line 24, and I can’t seem to pass children into the Provider. How does HOC work in ReasonML? What better place to find out than ReasonML’s discord chat.

Within minutes @alexfedoseev messages me his repo as an example using context and HOC.

Following his code I end up with 2 files — a reusable ReactContext with [bs.obj] and an ExperimentContext.re that will now render children, a working ReasonReact Context with HOC.

All that’s left is to set the experiment Provider in the highest part of the tree that it is needed. Then I can access both the experiment name and sanitized name via the Consumer in any component lower than the Provider.

--

--