Skip to content

Commit 301c12d

Browse files
authored
Merge pull request #266 from diogomqbm/rescript-react-router-example
Add documentation for `RescriptReactRouter`
2 parents 1b38344 + 51a586a commit 301c12d

File tree

2 files changed

+144
-1
lines changed

2 files changed

+144
-1
lines changed

data/sidebar_react_latest.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
"components-and-props",
1111
"arrays-and-keys",
1212
"refs-and-the-dom",
13-
"context"
13+
"context",
14+
"router"
1415
],
1516
"Hooks & State Management": [
1617
"hooks-overview",

pages/docs/react/latest/router.mdx

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
---
2+
title: Router
3+
description: "Basic concepts for navigation and routing in ReScript & React"
4+
canonical: "/docs/react/latest/router"
5+
---
6+
7+
# Router
8+
9+
RescriptReact comes with a router! We've leveraged the language and library features in order to create a router that's:
10+
11+
- The simplest, thinnest possible.
12+
- Easily pluggable anywhere into your existing code.
13+
- Performant and tiny.
14+
15+
## How does it work?
16+
17+
The available methods are listed here:
18+
- `RescriptReactRouter.push(string)`: takes a new path and update the URL.
19+
- `RescriptReactRouter.replace(string)`: like `push`, but replaces the current URL.
20+
- `RescriptReactRouter.watchUrl(f)`: start watching for URL changes. Returns a subscription token. Upon url change, calls the callback and passes it the `RescriptReactRouter.url` record.
21+
- `RescriptReactRouter.unwatchUrl(watcherID)`: stop watching for URL changes.
22+
- `RescriptReactRouter.dangerouslyGetInitialUrl()`: get `url` record outside of `watchUrl`. Described later.
23+
- `RescriptReactRouter.useUrl(~serverUrl)`: returns the `url` record inside a component.
24+
25+
> If you want to know more about the low level details on how the router interface is implemented, refer to the [RescriptReactRouter implementation](https://github.com/rescript-lang/rescript-react/blob/master/src/RescriptReactRouter.res).
26+
27+
## Match a Route
28+
29+
*There's no API*! `watchUrl` gives you back a `url` record of the following shape:
30+
31+
<CodeTab labels={["ReScript", "JS Output"]}>
32+
33+
```res prelude
34+
type url = {
35+
/* path takes window.location.pathname, like "/book/title/edit" and turns it into `list{"book", "title", "edit"}` */
36+
path: list<string>,
37+
/* the url's hash, if any. The # symbol is stripped out for you */
38+
hash: string,
39+
/* the url's query params, if any. The ? symbol is stripped out for you */
40+
search: string
41+
}
42+
```
43+
```js
44+
// Empty output
45+
```
46+
47+
</CodeTab>
48+
49+
So the url `www.hello.com/book/10/edit?name=Jane#author` is given back as:
50+
51+
<CodeTab labels={["ReScript", "JS Output"]}>
52+
53+
```res prelude
54+
{
55+
path: list{"book", "10", "edit"},
56+
hash: "author",
57+
search: "name=Jane"
58+
}
59+
```
60+
```js
61+
// Empty output
62+
```
63+
64+
</CodeTab>
65+
66+
## Basic Example
67+
68+
Let's start with a first example to see how a ReScript React Router looks like:
69+
70+
<CodeTab labels={["ReScript", "JS Output"]}>
71+
72+
```res
73+
// App.res
74+
@react.component
75+
let make = () => {
76+
let url = RescriptReactRouter.useUrl()
77+
78+
switch url.path {
79+
| list{"user", id} => <User id />
80+
| list{} => <Home/>
81+
| _ => <PageNotFound/>
82+
}
83+
}
84+
```
85+
```js
86+
import * as React from "react";
87+
import * as User from "./User.bs.js";
88+
import * as RescriptReactRouter from "@rescript/react/src/RescriptReactRouter.bs.js";
89+
import * as Home from "./Home.bs.js";
90+
import * as NotFound from "./NotFound.bs.js";
91+
92+
function App(Props) {
93+
var url = RescriptReactRouter.useUrl(undefined, undefined);
94+
var match = url.path;
95+
if (!match) {
96+
return React.createElement(Home.make, {});
97+
}
98+
if (match.hd === "user") {
99+
var match$1 = match.tl;
100+
if (match$1 && !match$1.tl) {
101+
return React.createElement(User.make, {
102+
id: match$1.hd
103+
});
104+
}
105+
106+
}
107+
return React.createElement(NotFound.make, {});
108+
}
109+
110+
var make = App;
111+
112+
export {
113+
make ,
114+
115+
}
116+
```
117+
118+
</CodeTab>
119+
120+
## Directly Get a Route
121+
122+
In one specific occasion, you might want to take hold of a `url` record outside of `watchUrl`. For example, if you've put `watchUrl` inside a component's `didMount` so that a URL change triggers a component state change, you might also want the initial state to be dictated by the URL.
123+
124+
In other words, you'd like to read from the `url` record once at the beginning of your app logic. We expose `dangerouslyGetInitialUrl()` for this purpose.
125+
126+
Note: the reason why we label it as "dangerous" is to remind you not to read this `url` in any arbitrary component's e.g. `render`, since that information might be out of date if said component doesn't also contain a `watchUrl` subscription that re-renders the component when the URL changes. Aka, please only use `dangerouslyGetInitialUrl` alongside `watchUrl`.
127+
128+
## Push a New Route
129+
From anywhere in your app, just call e.g. `RescriptReactRouter.push("/books/10/edit#validated")`. This will trigger a URL change (without a page refresh) and `watchUrl`'s callback will be called again.
130+
131+
We might provide better facilities for typed routing + payload carrying in the future!
132+
133+
Note: because of browser limitations, changing the URL through JavaScript (aka pushState) cannot be detected. The solution is to change the URL then fire a "popState" event. This is what Router.push does, and what the event watchUrl listens to.
134+
So if, for whatever reason (e.g. incremental migration), you want to update the URL outside of `RescriptReactRouter.push`, just do `window.dispatchEvent(new Event('popState'))`.
135+
136+
## Design Decisions
137+
138+
We always strive to lower the performance and learning overhead in RescriptReact, and our router design's no different. The entire implementation, barring browser features detection, is around 20 lines. The design might seem obvious in retrospect, but to arrive here, we had to dig back into ReactJS internals & future proposals to make sure we understood the state update mechanisms, the future context proposal, lifecycle ordering, etc. and reject some bad API designs along the way. It's nice to arrive at such an obvious solution!
139+
140+
The API also doesn't dictate whether matching on a route should return a component, a state update, or a side-effect. Flexible enough to slip into existing apps.
141+
142+
Performance-wise, a JavaScript-like API tends to use a JS object of route string -> callback. We eschewed that in favor of pattern-matching, since the latter in Rescript does not allocate memory, and is compiled to a fast jump table in C++ (through the JS JIT). In fact, the only allocation in the router matching is the creation of the url record!

0 commit comments

Comments
 (0)