A simple router for React.
npm install @ryancole/router
@ryancole/router
is a simple router for React. The main focus of the router
is to function in a reliable and predictable manner in both client and server
environments.
Concepts
The main concept of the router is that routes are an up-front, static resource.
The router operates on an array of route objects. You define your routes up
front.
A route is intended to be thought of as a complete "page" or "view" to be
rendered by React. The intention is that, when the URL pathname changes and this
router finds the appropriate React component to render, the component being
rendered is going to make up your complete application view so that you can
simply call ReactDOM.render
on the returned component. Nested views and such
can be achieved by using "template" components that compose your boilerplate
components and render your route component into it, etc.
import {routes} from "@ryancole/router";
export default routes([
{
path: "/",
loadComponent: () => System.import("../client/page/Home")
},
{
path: "/team",
loadComponent: () => System.import("../client/page/Teams")
},
{
path: "/team/:slug",
loadComponent: () => System.import("../client/page/Team")
}
]);
The router will provide the first route object that has a path
that matches
the requested URL pathname. The path
may use express-style parameters.
A route object must specify a loadComponent
function that returns the React
component to be rendered when this route is matched. loadComponent
must return
a then-able promise-like which resolves to the loaded React component.
import {match} from "@ryancole/router";
import createHistory from "history/createBrowserHistory";
const history = createHistory();
history.listen(renderLocation);
function renderLocation(location) {
const route = match(location, routes);
if (route) {
route.loadComponent(route, history).then(component => {
ReactDOM.render(component, destination);
});
}
}
renderLocation(history.location);
The router will also check to see if the route's component has any data concerns
and will fetch the necessary data. A React component can implement a static
function called getInitialProps
if it needs to have data fetched prior to
being rendered. This getInitialProps
function will be called on both browser
and server and will provide whatever is returned as props to the route's
component.
export default function Team({team}) {
return (
<Template>
<h1>{team.name}</h1>
</Template>
);
}
Team.getInitialProps = async ({slug}) => {
const team = await Teams.getBySlug(slug);
return { team };
}