React Router V6. What’s New?

Hilda Diana
3 min readDec 13, 2021

--

A new React Router version was released early November: React Router V6! Since I didn’t find many blogs writing about it, I decided to write my own. Hopefully others will find it helpful. I’ll focus on three of these changes, which I used for a project I worked on: <Switch>, <Route element>, and <Route exact>. For a complete tutorial and docs of all the V6 changes, checkout: reactrouter.com

Installation

We install the latest version 6 using either of the two options below in the terminal. Both will work.

$ npm install react-router-dom@6

$ npm install react-router-dom@latest

To check that it was installed, we go to our package.json file. The latest version should appear under ‘react-router-dom’. In the example below, that is in line 11:

1. <Switch>

Gone ✅. Yay! Previously the advantage of using <Switch/> was that it served as a wrapper. So whenever one navigated to a URL within an application, it looked for matching pieces from the <Route> it wrapped. Here’s an example of that, where <Switch> wraps three routes and makes sure that only one of the routes is loaded at the same time instead of all matching routes.

Now, React Router V6 introduces us to a <Routes> component, which also has a new prop called element.

2. <Route element>

Another feature of V6 is that we longer use component. Instead we use the element prop on Route. What this does is allow us to pass a React component rather than just the name of that component. This makes it easier to pass props down the routes. In the example below, notice the new element prop with the dynamic value passed to element, which is what will be rendered. Notice the differences between the image above and the one below:

  • V6: element

Each route becomes a self closing component.

3. <Route exact>

Also gone! In V5, we needed exact when evaluating paths and choosing a route to load. Otherwise, using the example above, it will match a route that starts with “/dishes”. So it will load both components: (/dishes and /dishes/new).

V6, on the other hand, looks for the exact matches without the use of exact prop. Instead of adding exact, we can now use * at the end of the route path to indicate they match deeply. Furthermore, routes can be in any order we want since the router will automatically detect the best route for the current URL.

In summary, <Switch> is replaced with <Routes>, which comes with a new component: element. <Route exact > is also gone because React Router will always look for the exact path passed.

Additional Resources:

--

--

Hilda Diana

Full Stack Software Engineer with knowledge and passion to build applications and projects for a wide range of users while prioritizing users with disabilities.