My previous article on upgrading to react-router alpha4 is still getting a lot of traffic. Below is an updated version of that post for the release version of react-router v4.

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.

Migrating

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

npm install --save react-router
npm install --save react-router-dom

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 realised 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/>.