React Tricks Miniseries 3: How to setup Routes
Uriel Bitton
Posted on April 28, 2022
React Routes
React (relatively) recently shipped a new version of react-router-dom, V6. This means using routes has completely changed. If you have tried implementing routes in your react app with the V6, you must have run into this issue.
Here's how we can use routes in the new V6 version.
The old routing
With V5 of react router dom, we instantiated routes by having a Router component and inside it we insert the Switch component and nesting inside our routes like so:
<Router>
<Switch>
<Route path="/">
<Homepage />
</Route>
<Route path="/about-us">
<AboutUs />
</Route>
</Switch>
</Router>
That all changes in V6. In my opinion it's actually enhanced and more intuitive.
Now there is a complex and sophisticated system of rending subroutes and matching exact Vs no exact routes, But i won't get into that. You can read and get familiar with these features here:
react-router-dom-v6-docs
The changes are like the following:
<Router>
<Routes>
<Route index element={<Homepage />} />
<Route path="about" element={<AboutUs />} />
</Routes>
</Router>
The first main change is the home page component accepts a prop called index instead of a path prop.
The second change is that we pass our component inside the element prop.
The third main change is that there is no more "exact" prop. This is because by default all routes are exact, meaning they match only the exact path. To make a global match we can use asterisks like so
<Route path="/services/*" element={<OtherServices />} />
Here OtherServices is a component that will render when the path matches "services/any-url"
Conclusion
Implementing routes in V6 is more intuitive and allows more control using asterisks and makes for cleaner code.
What do you think of this version?
Posted on April 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.