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:
Index.re
— renders <App />
to #root
App.re
— the shell component, uses ReasonReactRouter.useUrl()
to display the correct pageHome.re
— renders text of “Home page”Second.re
— renders text of “Second page”Third.re
— renders text of “Third page”Nav.re
— contains a list of links to each pageLink.re
— makes use of ReasonReactRouter.push()
on the clicked linkThe 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.