A Route by any Other Name

If your router doesn’t support named routes then you’re missing out. Without named routes, changes to URLs ripple throughout your code base. Named routes insulate your code from URL changes, allowing you to safely delay decisions about how your URLs should look.

When the React Router brought in async configuration it dropped support for named routes. That so few people complained about their removal I attribute to that router’s flawed implementation of them. To see how good named routes can be I’ll show you how they work in my Navigation router.

Imagine we’re tasked with displaying a paged list of items. Our Navigation router configuration will start out looking something like:

var stateNavigator = new StateNavigator([
  {key: 'list', route: 'list'}

We can then use the NavigationLink component to build a Hyperlink that navigates to the second page of items as shown below. You can see that, because we’re using named routes, we don’t hard-code the URL. Instead we pass the key from the configuration together with the page number and leave it up to the router to generate the URL for us:

<NavigationLink stateKey="list" navigationData={{page: 2}} />

This generates a URL of ‘/list?page=2’. We’re happy to live with this scruffy URL throughout development but it needs smartening up before we go live.

We’ll make the URL read ‘/items/2’ instead of ‘/list?page=2’. With the React Router’s (now defunct) named routes support, we couldn’t change page number from a query string to a route parameter without corresponding code changes. But with the Navigation router we can, because our application code isn’t aware of where in the URL the page number lives:

var stateNavigator = new StateNavigator([
  {key: 'list', route: 'items/{page}'}

The icing on the cake is for the URL back to the first page to be ‘/items’ instead of ‘/items/1’. With any other router this would require a code change. With the Navigation router this is only a configuration change, because we can specify a default value for the page number:

var stateNavigator = new StateNavigator([
  {key: 'list', route: 'items/{page?}', defaults: {page: 1}}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s