<Router>
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 'routescape';
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.
Custom routing
The location provider component <Router>
can be used to redefine the route matching behavior.
import {Route, Router, getPath} from 'routescape';
class PathRoute extends Route {
getHref(location) {
// disregard `search` and `hash`
return getPath(location, {search: false, hash: false});
}
}
let App = () => (
<Router location={new PathRoute(url)}>
<App/>
</Router>
);
By default, routing relies on the entire URL. In this example, we've redefined this behavior to disregard the search
and hash
portions of the URL.
Extending the Route
class gives plenty of room for customization. This approach allows in fact to go beyond the URL-based routing altogether.
← Converting HTML links to SPA route links | Unknown routes →