Random UTF-8 characters

Home

09 Oct 2016 in reactrouterjavascript

Upgrading to react-router v4

This article was written when react-router alpha4 was the most recent release. If you are using the 4.0.0 release or higher please read this post: http://rants.broonix.ca/updated-upgrading-to-react-router-v4-2/

About a month ago, the react-router team released version 4 of react-router. This version is a complete rewrite of how routing is handled. This new version has been mostly well received, with a few vocal complaints.

I decided to take a little bit of time and migrate my reactit demo app to v4 of react-router. I'll outline what changes I had to make for v4 as well as my thoughts on the new approach.

==Note: At this time react-router v4 is alpha. You should not be using this in production. If you are using this post as a migration guide, you can't say I didn't warn you!==

Migrating

Well, first things first. I installed the new version of react-router using npm.

npm install --save react-router@next

The big reason for this rewrite was 'Declarative Composability'. This means that routes are now just components. You might want to re-read that last sentence. This works really well in my demo app. The components themselves now define the composition of the UI.

Before all my routing was done in index.js. This is the same routing you see in most v2 apps.

The first thing I realized is that I can get rid of all this routing in index.js. We can just render the app and compose the UI based on the route. After removing all the routing index.js now looks like this:

When using v2, it was the route in index.js that injected the correct children to be rendered based on the route.

This is where v4 starts to shine. Now I can compose the UI based on the path as part of the App component. This is a much more concise way to define what is happening in the application.

While this is a very simple example with only two routes, you can quickly see the amount of forward thinking that has been put into v4. I'm already seeing some great use-cases that will be simpler (ex: side menus). It also feels more 'react' to have your routes be components.

Testing

In order to give routes to my components during testing, I simply wrapped them in <MemoryRouter/>.

As always this code is available on GitHub. You can see the commit that updates 'reactit' to react-router v4 right here: https://github.com/brookslyrette/reactit/commit/9cba5c3ac3205c7e3a36620a809d3c00fdb5ec20