React Router v6 - What's new?

Hi guys,

So recently, React Router V6 was released and it has many new and interesting features. Lets look into some of these new upgrades.

Goodbye Switch!

Previously, in React Router V6, we used the <Switch> component to wrap all of our Routes, now the the Switch component has been replaced by <Routes>. It is essentially the same thing as switch, however some new features have been added to the <Route> component it self.

Changes to the Route Component

There have been a couple of useful upgrades to the <Route> component.

1 - No need of exact.

In V5, you needed to put the exact prop on the component so that it goes to the particular route. However in V6, there is no need of this prop as React Router now always looks for the exact path without being told.

2 - Introducing the element prop

Previously, we used to pass the component in the Route as a child, or in other words, the component would be placed within the Route. In V6, this is no longer needed as you can simply pass the element prop in the route and place the component inside it. The pros of this are that you can simply inject whichever component one needs depending on its route rather than placing it in each route component.

V5 vs V6 code example:

The above mentioned upgrades are demonstrated in the comparison below.

React Router V5 code:

export default function App() {
  return (
    <div>
      <Switch>
        <Route path="/page1">
          <Page1/>
        </Route>
        <Route exact path="/page2">
          <Page2/>
        </Route>
      </Switch>
    </div>
  )
}

React Router V6 code:

export default function App() {
  return (
    <div>
      <Routes>
        <Route path="/page1" element={<Page1/>} />
        <Route path="/page2" element={<Page2/>} />
      </Routes>
    </div>
  )
}

As you can see, 3 changes can be noticed in the above code comparison, Use of Routes instead of Switch, removal of exact and use of the element prop.

These are some of the routing related upgrades. There are many more new features and changes that are covered in depth in my hupbages article.

Thank you for reading!. I hope you found out some new information regarding the changes in react router v6.
If you liked the post, you can buy me a coffee!
Buy Me A Coffee
Also, check out my hubpages articles.
Cheers:)

10