Skip to main content

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

jjinux said…
Another tip: if you're using react-router-bootstrap, make sure you're using version 0.24.2 or above.
jjinux 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

Popular posts from this blog

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from