DEV Community

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

Posted on • Edited on

5 2

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:

<Router>
  <Switch>
    <Route path="/">
      <Homepage />
    </Route>
    <Route path="/about-us">
      <AboutUs />
    </Route>
  </Switch>
</Router>
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:
react-router-dom-v6-docs

The changes are like the following:

<Router>
  <Routes>
    <Route index element={<Homepage />} />
    <Route path="about" element={<AboutUs />} />
  </Routes>
</Router>
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"

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?

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay