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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more