Search code examples
javascriptreactjsreact-router-dom

React router dom navigating to wrong path


We are using React-Router-DOM v6.19.0 and there are two you can find below.

<Route path="/route1/*" element={<RouteOneList />} />
<Route path="/route1/:one/:two/:three" element={<RouteAnother />} />

and in RouteOneList it has sub routes

<Route path="/add/:type/:id" element={<AddComponent />} />

Here I am trying to access

"/route1/add/test/1" - It is supposed to load AddComponent but it's falling into <RouteAnother /> component.

Is there any way tackle this problem? I have tried changing the order but that also not helped me.


Solution

  • Issue

    The issue here is that the Routes component only handles matching the routes it renders directly. The "/route1/add/test/1" path can be matched by the "/route1/:one/:two/:three" path and so that is what is matched and rendered.

    Solution

    Based on your comment in another answer that RouteOneList is a layout with a button I suggest actually using it as a layout route. Instead of RouteOneList rendering descendent routes it should instead render an Outlet component for nested routes. This is so the main Routes component can know of and match "/route1/:one/:two/:three" and "/route1/add/:type/:id".

    import { Outlet } from 'react-router-dom';
    
    const RouteOneList = () => (
      <>
        ...
        <Outlet />
        ...
      </>
    );
    
    <Routes> // <-- knows of all routes for matching/rendering
      <Route path="/route1">
        <Route element={<RouteOneList />}> // <-- layout route
          <Route path="add/:type/:id" element={<AddComponent />} />
        </Route>
        <Route path=":one/:two/:three" element={<RouteAnother />} />
      </Route>
    </Routes>
    

    Demo

    Edit react-router-dom-navigating-to-wrong-path