@ryancole/router

A simple router for react.

Usage no npm install needed!

<script type="module">
  import ryancoleRouter from 'https://cdn.skypack.dev/@ryancole/router';
</script>

README

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. You can take the requested URL and match it against your routes and get the exact route that should be rendered.

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.

There is no route nesting, like react-router v3, and there are no floating route components, like react-router v4. Because of this, there is a clear place to perform code splitting and asynchronous loading of split bundles.

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")
  },
  {
    path: "*",
    isNotFound: true,
    loadComponent: () => System.import("../client/page/NotFound")
  }
]);

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 should return a Promise that resolves to the loaded React component.

import {match} from "@ryancole/router";
import createHistory from "history/createBrowserHistory";

const history = createHistory();

// on route change, re-render
history.listen(renderLocation);

function renderLocation(location) {
  const matched = match(location, routes);
  if (matched) {
    const {route} = matched;
    route.loadComponent(matched, history).then(Component => {
      ReactDOM.render(<Component />, destination);
    });
  }
}

// render current route
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. If implemented, the getInitialProps return value object will be provided to the route component as props.

export default function Team({team}) {
  return (
    <Template>
      <h1>{team.name}</h1>
    </Template>
  );
}

Team.getInitialProps = async ({slug}) => {
  const team = await Teams.getBySlug(slug);
  return { team };
}

Lastly, there is a convenience component for linking to your routes. You may import Link and use it to push new paths. If the current URL pathname matches the Link destination, then it will apply a custom class name.

import {Link} from "@ryancole/router";

export default function Navbar() {
  return (
    <nav className="nav nav-inline">
      <Link to="/" className="nav-link" activeClassName="font-weight-bold">
        Home
      </Link>
      <Link to="/team" className="nav-link" activeClassName="font-weight-bold">
        Teams
      </Link>
    </nav>
  );
}