Search code examples
reactjsreact-routerreact-router-dom

how to handle multiple routes that match the same path


      <Routes>
        <Route path="cheese">
          <Route index element={<Home />} />
          <Route path="*" element={<Home />} />
        </Route>
        <Route path=":category">
          <Route index element={<Article />} />
          <Route path=":id">
            <Route index element={<Article />} />
            <Route path="*" element={<Article />} />
          </Route>
          <Route path="*" element={<Article />} />t
        </Route>
      </Routes>

In the above, if the path of the url is /cheese/12345, it is the second router that is matched, hence the element <Article /> is returned.

How to correct this?

I am using React Router v6


Solution

  • react-router-dom@6 routes always exactly match paths, "/cheese/12345" is exactly matched by the very general "/:category/:id" route path rather than the specific "/cheese" path.

    The nested <Route path="*" element={<Home />} /> under the parent "/cheese" route should also be matched by "/cheese/12345".

    If you want to de-duplicate the Home component on two routes and for the first route to match "/cheese" and also any "sub-route"/descendent path then it should have a wildcard "*" matcher appended to the path.

    Example:

    <Routes>
      <Route path="/cheese/*" element={<Home />} />
      <Route path="/:category/:id" element={<Article />} />
    </Routes>
    

    If you would like to also capture any cheese id values then you can specify an optional path param (only RRDv6.5+).

    <Routes>
      <Route path="/cheese/:id?" element={<Home />} />
      <Route path="/:category/:id" element={<Article />} />
    </Routes>
    

    Edit how-to-handle-multiple-routes-that-match-the-same-path