Caveats on migrating to React Router 4

As you may know, React Router had a major update several months ago. It was more than just an API change, it’s a paradigm shift towards incorporating React Router inside React. Now you don’t need a separate hierarchy of routes anymore: all your routes are common React components and you can use them anywhere inside your component tree. You can check out this video where Michael Jackson describes their journey to the current state of things. Here I want to cover some caveats that you may encounter while migrating to React Router 4 from versions 2 or 3.

Caveat #1: history is not there anymore

First of all, history now resides in the dedicated history package. Second, you need to call createBrowserHistory or createMemoryHistory depending on your evironment (browser or server).

Caveat #2: you shoud wrap all inner content with div

This rule applies to any router you choose to use (BrowserRouter, StatiicRouter, etc.). You need to wrap everything inside Router with div like so:

<Router history={history}>
<App />

Caveat #3: use base Router to sync with your store

If you want to pass your history explicitly (in case you want to sync it with your store), you need to use base Router component instead of BrowserRouter, for instance.

Caveat #4: code splitting

With React Router version 4 code splitting is also dedicated to components. Here we have several options like react-loadable and react-async-component. I prefer the first one, since it is easier to configure, especially on the server side. Here is a nice article by its’ creator to dig deeper.

Caveat #5: no query object

This functionality is now external to React Router (personally, I don’t like it). The solution is to use the combination of qhistory and some parsing package like qs. The final code would be:

import { createBrowserHistory} from 'history';
import qhistory from 'qhistory';
import { stringify, parse } from 'qs';
const history = createBrowserHistory(); 
export default qhistory(  history,  stringify,  parse);

Hope that’ll help someone in the future. If you need a detailed guide on how to migrate to React Router 4 you can check this article.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.