Fork me on GitHub

Ahad Bokhari

What Routers Do

Edit   ·   454 words

As you know, many modern front end applications are basically a tree of components. Some of these components are reusable UI components (e.g., menu, lists), and some are application components, which represent screens or some logical parts of the application. The router cares about application components, or, to be exact, about their arrangements. For simplicity’s sake lets call these component arrangements router states. So a router state defines what a user can see on the screen.

Take a look at the example below of a router configuration defining all the potential states of an application.

[
  {
    path: ':root',
    children: [
      {
        path: '',
        component: MessagesComponent
      },
      {
        path: ':id',
        component: MessagesComponent,
        children: [
          { path: 'convos', component: MessagesComponent },
          { path: 'convos/:id', component: MessagesComponent }
        ]
      }
    ]
  },
  {
    path: 'message',
    component: ComposeComponent
  },
  {
    path: 'message/:id',
    component: ComposeComponent
  }
]

Don’t worry about the details, the take away should be that the router configuration is a tree. with each node representing a route.

Router State

A router state is a subtree of the configuration tree. When you configure the routing for an app, you are laying out the various states the application can be in, and informing the application what to display and do when a specific route is encountered (paramaters of that route can change as well). Your app’s routing mechanism should fully embrace the state-machine nature of a routing system. This allows you to define states, and transition your application to those states. The real win is that it allows you to decouple nested states, and do some very complicated layouts in an elegant way.

Navigation interprets a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link. You can navigate imperatively when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. And the router logs activity in the browser’s history journal so the back and forward buttons work as well. These are all hallmarks of a single page application.

URL & Summary

The URL bar provides a massive advantage for web applications over native ones you find on your mobile phones. It allows us to reference states, bookmark them, and share them with our friends. In a well-behaved web application, any application state transition results in a URL change, and any URL change results in a state transition. In other words, a URL is nothing but a serialized router state.