The router that ships with ReasonReact is simple and flexible. Still, it would have helped me to see a complete working example. The blog posts I found (Routing in ReasonReact by Kyle Henderson and Routing in ReasonReact by A. Sharif) haven’t been updated since React Hooks were introduced.

I created the simplest example I could, using the router to switch between a few pages with a <nav>, which I guess I would call a “simulated multi-page application.”

You can see my deployed example application here. You can find the GitHub repo here.

The project has the following Reason files:

  1. Index.re — renders <App /> to #root
  2. App.re — the shell component, uses ReasonReactRouter.useUrl() to display the correct page
  3. Home.re — renders text of “Home page”
  4. Second.re — renders text of “Second page”
  5. Third.re — renders text of “Third page”
  6. Nav.re — contains a list of links to each page
  7. Link.re — makes use of ReasonReactRouter.push() on the clicked link

The key components are App and Link.

/* App.re */

type route =
  | Home
  | Second
  | Third;

[@react.component]
let make = () => {
  let url = ReasonReactRouter.useUrl();

  <div>
    <Nav />
    {switch (url.path) {
     | [] => <Home />
     | ["second"] => <Second />
     | ["third"] => <Third />
     | _ => <Home />
     }}
  </div>;
};

The url variable in App.re (holding the result of calling ReasonReactRouter.useUrl()) will change as the URL changes. url.path in the switch statement will be a list of of strings containing each segment of the URL path. So, for https://my-awesome-todo-app.com/second, it would be ["second"].

/* Link.re */

let handleClick = (href, _event) => {
  ReasonReactRouter.push(href);
};

[@react.component]
let make = (~name, ~href) => {
  <a onClick={handleClick(href)}> {React.string(name)} </a>;
};

The Link component in my example takes two props, name and href (e.g. <Link href="/second" name="Second" />). When the resulting anchor tag is clicked, ReasonReactRouter.push() will navigate to the provided href prop.

In summary, I used ReasonReactRouter.useUrl() to watch URL changes, and a switch statement to display a component based on the current URL path. I created a simple navigation component and a custom link component that uses ReasonReactRouter.push() to change the page based on which link gets clicked.

Here’s a link to the router documentation page. Here’s a link to the ReasonReactRouter code on GitHub, which contains inline documentation.