React Router

cory

Welcome to the Part 7 of this new series reviewing Cory House’s Pluralsight course Building Applications with React and Flux.

Cory is a Microsoft MVP in C#, founder of OutlierDeveloper.com, avid tech reader, and speaker.

He believes in clean code, pragmatic development, and responsive native UIs.
Building Applications with React and Flux is the prequel to Cory’s course Building Applications with React and Redux in ES6.

If you are new to React JS or React-Router, or prefer to do your development in regular JavaScript without using Babel and other tools that you don’t necessarily need, then this course is for you. Alternatively, check out the review of his other React course above.

Also in this series:

Part 1 – Introductory Topics

Part 2 – Environment Setup

Part 3 – React Core Concepts

Part 4 – Creating Components Introduction

Part 5 – React Lifecycle

Part 6 – React Composition

React Router

For small apps you won’t need a fully featured router, but as your application grows you’ll benefit from splitting it into multiple client rendered pages with deep linking.

In React Router, you declaratively configure your routes. React Router is inspired by the routing used in Ember JS.

You can find the official documentation on Github.

Route Configuration

Demo: Route Configuration

Cory creates routes.js and requires in React and React Router.

We define our routes using JSX, and importing each component in as each route handler.

We see how to set the path attribute to name our URLs as we like.

Demo: Bootstrapping

Earlier we created a bit of a mess in main.js, but we can now greatly simplify our code.

We see how to move our inline app component out to /components/app.js

We were handling our own child routing though our simple custom routing solution.

Now that we are using React Router, Cory replaces the Child handler with a RouteHandler.

RouteHandler is part of React Router.

Many changes are now appropriate for main.js, and Cory demonstrates:

  • Removing the references to Home, Authors and About
  • Removing our custom rendering code
  • Removing our IIFE
  • Importing our React-Router module and our routes component
  • Running the router with Router.run and calling React.render within here

Our application is now much cleaner, with better separation of concerns and no need to manage a switch statement.

Params and Querystrings

If you want to pass parameters in the URL, React Router supports you with this, automatically adding data to props.

This requires much less code than explicitly setting these yourself in your render functions, as Cory shows.

Dylan Companjen, a freelance front end web developer from the Netherlands, has contributed to several React Router examples, including a query params example: see app.js and index.html

The next episode will explore using Params and Querystrings as well as React Forms.

Links

React Router provides a link component, and we can use this in our JSX.

We set the to property to the name of the link that we want to link to.

There’s also a params property, and we can provide a JSON object of data that’s useful for the URL.

Cory shows us the code before and after compilation for the link.

We can also see a github code example here: active-links app.js

The link component effectively normalizes your links by abstracting away hyper references. We simply reference our routes by name.

Demo: Links

What do we mean by normalizing links and abstracting away from hyper references?

We see here that this is actually a simple concept.

Earlier, in header.js we had hard-coded our links. This is okay for small apps, but for large apps it’s simply likely to come back and bite us in the ass.

Cory imports the react-router module, references the link component and assigns it to a new variable Link.

Now we can replace:

  • The “a” anchor tag with “Link” and
  • “href” with “to”

We can simplify our links by removing the paths. For example “/#authors” now just uses our name “authors”.

When we run up the browser, we see that we’re no longer doing a full postback each time we click on a link.

Also if we want to update a link name later, e.g. from about to about-us, we only need to change this in one place.

For full details on how the Link component works, see the source code.

Demo: NotFoundRoute

If a user enters an invalid URL, we’d like to show a friendly error page.

Cory adds notFoundPage.js to the project, and there is nothing complicated going on here.

Then in routes.js we reference NotFoundRoute  and add this in our JSX. The handler for this is our new notFoundPage component.

When we run our app again and enter a faulty URL, we see “Page Not Found Whoops! Sorry, there is nothing to see here.” with a link back to our homepage.

This is an improvement, but it would be even better if it redirected for them automatically.

Redirects

We can do this by aliasing Redirect, and then creating a new Route specifying the from and to properties.

For full details on this module, see the Redirect source code.

Demo: Redirects

First we use Redirect for handling bad references, importing the Redirect component into routes.js and adding a Redirect in our JSX.

This example redirects from about-us to about.

We can also add Redirects for typos (e.g. awthurs) to their non typoed equivalents (e.g. authors).

Finally we see that we can redirect entire subdirectories to a particular URL.

Transitions

We sometimes want to run code before loading and unloading pages.

Cory explains the functions willTransitionTo and willTransitionFrom.

I could not find these functions in the latest version of React Router, and found this issue was raised on the loss of willTransitionTo.

For full details on the latest code see TransitionUtils.js

Demo: Transitions

Cory demonstrates willTransitionTo and willTransitionFrom. He may re-record this clip soon to demonstrate doing this in the latest version of React Router.

This creates hooks that display “Are you sure you want to enter a page this boring?” and “Are you sure you want to leave a page this exciting?”, a silly example but when we learn React Forms we will see how useful this technique can be.

Locations

There are two common approaches to doing client side routing:

Hash Location

HTML5 History Location via push state, replace state and pop state

We see that Hash Locations do not have the clean URLs that we get using HTML5 History location.

However Hash Location works in all browsers, whereas only recent browser versions support History. See Can I Use for the list of support for History.

Cory also explains that History can be used with React Router for server rendering.

For full details on the History module, see the latest source code.

Demo: Locations

We see this is just a one liner: adding Router.HistoryLocation as a parameter into our Router.run function.

We no longer have ugly looking # symbols in our URLs.

To use this, we must also configure our server to support clean URLs.

Also note the React-Router has changed since this course was recorded.

Navigation Mixin

This is another brief clip on Mixins. We learn that Router.Navigation and Router.State are two mixins included with React Router.

The navigation mixin allows us to:

  • Go to a new route
  • Replace current route
  • Go back to a previous URL
  • Create a URL to a route

Part 8 – React Forms is coming soon

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 )

Facebook photo

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

Connecting to %s