The One Thing you need to know about React Router 4

Sia Karamalegos
Clio + Calliope
Published in
2 min readMay 16, 2017

--

I finally started a new project using React Router 4. It’s no secret that the churn between versions has been pretty high, and version 4 is no different. However, I think the team at React Training has come a long way, and this version is definitely the best, and worth your time to learn.

For someone picking up React Router 4 for the first time, it’s probably very intuitive. For the rest of us, we may be getting hung up on the basics because we didn’t realize the fundamental change…

“Routes” aren’t really routes, they are just components.

Re-read that. Let it sink in. Repeat. Again.

Routes are now more like components that simply conditionally show or hide a target component or element based on whether the current URL matches the given path. If you focus on this key point, all the features and functionality that the new format gives you become so much more intuitive to understand.

Let’s take a look at a basic example before we dive too much further in:

Apply what you already know about Router to BrowserRouter (hence the named import), and Link works the same as well.

To get a deeper understanding of Route, I highly recommend diving directly into the API docs. The quick start and basic examples sections skim over a lot of the details. You have three different ways (through props) to tell aRoute what to render: a target component, or functions in render or children that return valid nodes. Note that children always returns the given node whether there is a match or not. It’s convenient for animation and cases like when we only want to modify a className based on the route but everything else still needs to render.

We call the BrowserRouter once in an application, usually at a high level (just above where we first need to start defining routes and links).

In the “old” days, we typically defined routes all in one file. Now, you can put them closer to where they should belong, composing your application based on the URL match logic. For example, say two different geographical areas of your application need to contain content that varies based on the URL. You can define two routes (or as many as you need) to match the same URL in different parts of your application.

A Route helps you compose your React applications in a more “React” way. No more mental acrobatics to try fit a traditional routing model with a React component tree model. Remember…

“Routes” aren’t really routes, they are just components.

The opportunities are endless.

If you liked this story, give it a💚 to share the love.

--

--

Sia Karamalegos
Clio + Calliope

Google Developer Expert in web technologies, traveler, code teacher, endurance racer, speaker, dog lover, crochet pattern designer, New Orleanian