ReasonReact

ReasonReact

  • Docs
  • Try
  • Examples
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›ReactJS Idioms Equivalents

Getting Started

  • What & Why
  • Installation
  • Intro Example

Core

  • Components
  • JSX
  • Event
  • Style
  • Router
  • ReactDOM
  • Refs in React
  • Testing components

Hooks

  • useState
  • useReducer
  • useEffect
  • Custom Hooks

ReactJS Idioms Equivalents

  • Invalid Prop Name
  • Props Spread
  • Component as Prop
  • Ternary Shortcut
  • Context
  • Error boundaries

FAQ

  • I'm Having a Type Error
  • I Really Need Feature X From ReactJS
  • I want to create a DOM element without JSX
Edit

Context

In order to use React's context, you need to create two things:

  1. The context itself
  2. A context provider component
/** as a separate file: ContextProvider.re */

// 1. The context itself
let themeContext = React.createContext("light");

// 2. The provider
include React.Context; // Adds the makeProps external
let make = React.Context.provider(themeContext);
/** or inside any other module */

// 1. The context itself
let themeContext = React.createContext("light");

// 2. The provider component
module ContextProvider = {
  include React.Context; // Adds the makeProps external
  let make = React.Context.provider(themeContext);
};

That will give you a ContextProvider component you can use in your application later on, by wrapping any component with ContextProvider, to have access to the context value inside the component tree. To know more about Context, check the createContext page of the React.js documentation and when to use it.

/** App.re */
[@react.component]
let make = () =>
  <div>
    <ContextProvider value="light">
      <ComponentToConsumeTheContext />
    </ContextProvider>
  </div>

Then you can consume the context by using the React.useContext hook

/** ComponentToConsumeTheContext.re */
[@react.component]
let make = () => {
  let theme = React.useContext(ContextProvider.themeContext);

  <h1>theme->React.string</h1>
}

Binding to an external Context

Binding to a Context defined in a JavaScript file holds no surprises.

/** ComponentThatDefinesTheContext.js */
export const ThemeContext = React.createContext("light");
/** ComponentToConsumeTheContext.re */
[@bs.module "ComponentThatDefinesTheContext"]
external themeContext: React.Context.t(string) = "ThemeContext";

[@react.component]
let make = () => {
  let theme = React.useContext(themeContext);

  <h1>theme->React.string</h1>
}
← Ternary ShortcutNext →
  • Binding to an external Context