JavaScript: Porting from React Router v2 to v4 (with tips for Enzyme and MobX)

I recently ported a large app from React Router v2 to v4. It was hard. I jotted down some notes in case you have to do the same thing.

First of all, start with the video, and look around in the Quick Start. The video will explain why v4 is better, and the Quick Start has a bunch of examples that you may find useful. I'm not going to duplicate all that knowledge. I'm just going to touch on some details.

Here's a little utility to configure the default routing configuration:

import $ from 'jquery';
 
/**
 * This is the default configuration for React Router v4.
 * 
 * Usage:
 * 
 *     <Router { ...getDefaultReactRouterConfig() }>
 */
export default function getDefaultReactRouterConfig() {
    const args = {},
        href = $('base').attr('href');
 
    // Make sure to strip the trailing slash from the base href; otherwise, it causes
    // a double slash issue on route changes to the root route. It is also not
    // possible to not have the trailing slash at the end of the base href,
    // since it breaks regular a href clicks by preventing a page reload.
    // E.g. we need `<base href="/message/" />` yet `basename: "/message"`.
    if (href) {
        args.basename = href.replace(/\/$/, '');
    }
 
    return args;
}

Here's how to use it:

import { BrowserRouter as Router, Route } from 'react-router-dom';
...
<Router { ...getDefaultReactRouterConfig() }>

We decided that all of our routes should use exact unless they are branches.

If you do not use exact, you should have your most specific routes first, and your least specific routes last.

Each level of the routing tends to use a switch statement like this:

<Switch>
    <Route exact path="/" component={ IntroductionRoute } />
    <Route path="/layout/" component={ LayoutRoute } />
    <Route path="/components/" component={ ComponentsRoute } />
    <Route exact path="/how-we-work/" component={ HowWeWorkRoute } />
    <Route exact path="/changelog/" component={ ChangelogRoute } />
    <Redirect to="/" />
</Switch>

If you're working on a nested route, you have to make the URLs more "relative":

<Switch>
    <Route exact path={ this.props.match.path } component={ LayoutIndexRoute } />
    ...
    <Redirect to={ this.props.match.path } />
</Switch>

If you're writing a component, and it's part of a Route, you don't need to do anything special to receive objects like history, match, etc. They'll be passed as props. However, if you're a component that's nested a few layers deep, you'll need to use the withRouter higher order component in order to get those things:

@inject('store')
@withRouter
@observer
@cssModules(styles)
export default class ActionsButton extends Component {
    static propTypes = {
      history: PropTypes.object,
        ...
    };
    ...
}

Note, although we're using withRouter as a decorator, it's just a function wrapper, so you don't need to use it as a decorator.

If you're using Enzyme, and you're using shallow, keep in mind that by adding another layer, you'll need to "unwrap" it in your tests. If you're using MobX providers as well, you have two layers to unwrap. Use .wrappedComponent to get rid of the @inject layer from MobX, and use .WrappedComponent to get rid of the @withRouter layer from React Router. Then, just pass the necessary objects as props:

wrapper = shallow(
    <UsersPagination.wrappedComponent.WrappedComponent
        store={ store }
        history={ history } />,
);

If you're using Enzyme and mount, and your component is using @withRouter or <Link> or doing something else that expects a router to be in the context, you'll need to put one there in your tests. The MemoryRouter was created for this purpose:

wrapper = mount(
    <MemoryRouter>
        <IndexRoute location={ { pathname: '/path/' } } />
    </MemoryRouter>,
);

If you're using Enzyme and mount, and you're also trying to pass things via context, but you have wrappers like @withRouter or @inject in the way, you're going to have a problem. Although you can pass extra context data to Enzyme's mount function, unless the outer wrapper is expecting that context data, it'll just throw it away. Hence, you'll need to write code that looks like:

wrapper = mount(
    <MemoryRouter>
        <IndexRoute location={ { pathname: '/path/' } } />
    </MemoryRouter>,
    {
        context: { store },
        childContextTypes: {
            store: PropTypes.object.isRequired,
        },
    },
);

If you're using Enzyme and wrappers like @withRouter and/or @inject, and you're using .find, you'll need to unpack those layers (as mentioned above):

expect(wrapper.find(UserCard.wrappedComponent.WrappedComponent).node.isRemoveUserModalOpen).toBeFalsy();

If you have code that used to use props.router.push, you'll need to change that to props.history.push. As mentioned above, you'll need to get access to the history object, either by being the component used with Route, or by using @withRouter.

If you have code that uses a location object rather than a location string, and you're using location.query, you'll need to change that to use location.search. However, location.search is now a string, not an object. Hence, you'll need to take care of serializing to and from a query string. Install the qs library via npm (which is what React Router v2 used under the covers), and do the serialization like this:

import qs from 'qs';
...
const searchObj = qs.parse(this.props.location.search.replace(/^\?/, ''));
...
this.props.history.push({
    pathname: this.props.location.pathname,
    search: qs.stringify(searchObj),
});

I know this has more to do with MobX than React Router v4, but since I'm documenting all the things that bit me while doing a large migration, permit me to document the following: be careful of what you put into MobX stores. Store "data". Don't store bits of content generated by JSX, and don't store references to components (i.e. classes). Also keep in mind that if you store data in a MobX store as observable data, MobX is going to transform that data into observable data.

I know that sounds silly, and I really, really like MobX in general, but every once in a while, it can surprise you. I had a normal, module-level object. It was used to setup the navigation. Hence, it had some paths, some titles, and some React components in it. Some other code was taking parts of that object, and putting it in a MobX store. Hence, I ended up with an observable object when I thought I had a plain object, and I ended up with a component class in my store. Hence, I ended up with an esoteric error message, "Cannot call a class as a function”. Anyway, moving on...

Imagine you have a routing setup with 3 levels of routing. In React Router v2, all the routing configuration would be in one file, and then the routing component in the middle of the hierarchy would look something like:

{ this.props.children }

But with React Router v2, the routing configuration is nested throughout your hierarchy, and that code gets replace with more routing such as:

<Switch>
    <Route exact path={ this.props.match.path } component={ LayoutIndexRoute } />
    ...
    <Redirect to={ this.props.match.path } />
</Switch>

In React Router v2, there was a little-used feature where you could use "components=" such as:

<Route path="components/" components={ { main: ComponentsRoute, sideFooter: ComponentsLegend } } />

In React Router v4, you don't just have one routing configuration, but the routing configuration can be spread across the app. You might even have some configuration from the main part of your app, and some different configuration for the sidebar:

{ hasSideNav ?
    <Col md={ 3 }>
        <SideNav items={ this.uiStore.sideNav.items }
                 rootPath={ this.uiStore.sideNav.rootPath } />
        <Route path="/components/" component={ ComponentsLegend } />
    </Col> : '' }

There's a nice example in the docs for doing something like this.

If you were relying on React Router's applyRouterMiddleware and onUpdate functionality in order to control the scrollbar, you'll find that they ripped out a lot of that stuff. What they have now is documented here. I ended up writing some code like:

export const ScrollToHash = props => {
    const { hash } = window.location;
    if (hash) {
        setTimeout(() => {
            const id = hash.replace('#', '');
            const element = document.getElementById(id);
            if (element) {
                element.scrollIntoView(true);
            }
        });
    }
    return Children.only(props.children);
};
...
@observer
export default class MainRoute extends Component {
    render() {
        return (
            <ScrollToHash>
                <div>
                    ...
                </div>
            </ScrollToHash>
        );
    }
}

Ok, that's it. Special thanks go to Cansin for writing most of the code I was porting as well as for reviewing all of my code.

Comments

Shannon Behrens said…
Another tip: if you're using react-router-bootstrap, make sure you're using version 0.24.2 or above.
Shannon Behrens said…
If you want Prompt to prompt the user when they try to entirely leave the site, pay attention to this PR: https://github.com/ReactTraining/react-router/pull/4372