DEV Community

Cover image for React Tricks Miniseries 3: How to setup Routes
Uriel Bitton
Uriel Bitton

Posted on • Updated on

React Tricks Miniseries 3: How to setup Routes

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:

    <Route path="/">
      <Homepage />
    <Route path="/about-us">
      <AboutUs />
Enter fullscreen mode Exit fullscreen mode

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:

The changes are like the following:

    <Route index element={<Homepage />} />
    <Route path="about" element={<AboutUs />} />
Enter fullscreen mode Exit fullscreen mode

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 />} />
Enter fullscreen mode Exit fullscreen mode

Here OtherServices is a component that will render when the path matches "services/any-url"


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?

Top comments (0)