React Router V4 – Routes not rendering, possible solution

I upgraded an application from React Router v2 to v3, then v4. The upgrade to v3 was relatively painless. The upgrade to v4 caused a few headaches, due to multiple reasons:

  • React Router v4 split from just react-router and now has react-router-dom and react-router-native
  • As a side effect, the Link component moved from react-router out to react-router-dom, which made every component that had a <Link> in it stop working
  • <Route>s became decentralized, so they are moved inline with the components

I actually prefer the decentralized approach in v4, since it means less backtracking to find security, pre-rendering, post-rendering, or other additional “layers” in the route that aren’t specified in the actual component.

In many examples I looked at, they had code similar to:

<Route path=”/” component={Home} exact />
<Route path=”/about” component={About} />
<Route path=”/contact” component={Contact} />

Those examples worked, but when I tried to split things down further, they stopped working for anything but the first route. Why? No failed render attempts. No errors. No console info. Swapping the component rendered in the root path would display any component I wanted, so why wouldn’t it path match on the others?

The <Router> component / tag has to be around every possible route!

If you have multiple possible routes in downstream components, they need to be wrapped in a <Router> to render anything aside from the first <Route> listed. Wrapping my route definitions with it made everything work again.

<Router>
<div>
<Route path=”/” component={Home} exact />
<Route path=”/about” component={About} />
<Route path=”/contact” component={Contact} />
</div>
</Router>

Note: I imported my preferred router from react-router-dom, HashRouter as Router, to make the tag Router. It also works with BrowserRouter, which I am not using since we haven’t configured WebPack to work with it yet)