T8 React Router

URL provider

In the browser, the routing hooks like useRoute() assume that the current URL is the browser's one (as exposed with window.location), by default. A custom initial URL value can be set with the <Router> component, which is useful for environments lacking a global URL value, like with server-side rendering or unit tests.

<Router href="/intro">
  <App/>
</Router>

Now that we've set up a URL context, both route and at() returned from useRoute() inside the <App> component operate based on the router's href:

let { route, at } = useRoute();

console.log(route.href); // returns based on the router's `href`

⬥ The <Router>'s href prop value can be either a string URL or an instance of the Route class. The latter option can be used to redefine the default routing behavior (see the Custom routing behavior section). If the href prop value is omitted or undefined, <Router> falls back to the current URL in the browser.

⬥ With SSR in an express application, the URL context setup can be similar to the following:

import { renderToString } from "react-dom/server";
import { Router } from "@t8/react-router";

app.get("/", (req, res) => {
  let html = renderToString(
    <Router href={req.originalUrl}>
      <App/>
    </Router>,
  );

  res.send(html);
});