React Routing Debunked

THE MYTH: You can’t build a React web app without the React Router

The Reality

The React Router maintainers argue that your code will be a mess of branching logic (‘if’ conditions and ‘switch’ statements) if you don’t use their router. They construct an email application example with nested views to support their claim. But, it isn’t true. You can use any router with React without introducing branching logic. To show this, I’ve built the email example using my Navigation router:

The React Router is a templating library that associates components with routes. The top level route holds the template component which hosts the child route components. But the React Router is trying to solve a problem that doesn’t exist, because React supports templates natively. Here’s an example of a React template, written as a functional stateless component:

var App = () => <div id="content"></div>;

You don’t need the React Router to ensure the correct component is loaded when a route is hit. All routers notify you when the route changes. To load the right component without introducing branching logic, you add separate listeners to the individual route change events. In the email example, when the ‘inbox’ route is hit, you load the Inbox component into the ‘content’ placeholder in the App template:

ReactDOM.render(<App/>, document.body);
ReactDOM.render(<Inbox/>, document.getElementById('content'));

If you use the React Router, then you can’t pass props into your components. With any other router you can, because it’s up to you, and not the router, to create your components. The example’s Inbox component needs to display a list of messages. The React Router has no choice but to hold the list in the component’s internal state. But, by using another router, you can follow the React way and pass it in as props instead:

<Inbox messages={messages} />

I’ve debunked the myth that you can’t build a React app without the React Router. You don’t have to worry that your code will turn into a branching mess without it. You’ve seen that any other router gives you back control over your components. So, you can ditch state in favour of props. The components in my email application example are all functional and stateless. The ones from the React Router documentation aren’t.


2 thoughts on “React Routing Debunked

    1. Thanks for the comment, Ross. You’d end up with a lot of branching in your createElement implementation 😉 Besides, why use a router that makes you jump through hoops just to pass props?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s