How to use React Context in ReScript

According to the documentation, this is a context file.

/** ContextProvider.re */
let themeContext = React.createContext("light");

include React.Context; // Adds the makeProps external
let make = React.Context.provider(themeContext);

But makeProps is not exported from this file as a result

<ContextProvider value="light">
...
</ContextProvider>

compiler throws an error as makeProps cant be found.
https://rescript-lang.org/try?code=PQKhAIGEHsDsBcCmAPeAFATtAbgSwCaIYB0Gi4IwAUADaLzjwAWiAtojAigwLzgBKiAIYBjeMRFkhSTklQAKAEQ1cAcybxFASgDcVKrlgiaAV0IDhY4rO47wwYOACC+fAGdGLcKyEBrRJjQAA4e3ESwQjS09N5+5HyCouI2qMRBWHiEGPLMbBxwcvC6QA

Yep, because you need a react.component wrapper and pass the provided prop down to the provider:

module ThemeContext = {
  let context = React.createContext("light")

  module Provider = {
    let provider = React.Context.provider(context)

    @react.component
    let make = (~value, ~children) => {
      React.createElement(provider, {"value": value, "children": children})
    }
  }
}

@react.component
let make = () => {
  <ThemeContext.Provider value="dark">
    <div/>
  </ThemeContext.Provider>
}
1 Like