T8 React Router
Location provider
Server-side rendering and unit tests are the examples of the environments lacking a global location (such as window.location
). They are the prime use cases for the location provider, <Router>
.
Let's consider an express application route as an example:
import { renderToString } from "react-dom/server";
import { Router } from "@t8/react-router";
app.get("/", (req, res) => {
let html = renderToString(
<Router location={req.originalUrl}>
<App/>
</Router>,
);
res.send(html);
});
The value passed to the router's location
prop can be accessed via the useRoute()
hook:
let { route, withRoute } = useRoute();
console.log(route.href); // returns the router's `location`
Both route
and withRoute()
returned from useRoute()
operate based on the router's location
.
<Router>
can be used with client-side rendering as well. In most cases, it is unnecessary since by default the route context takes the global location from window.location
if it's available.