Search code examples
react-routernavigationreact-router-dom

How can i use one Route for all subRoutes in react-router-dom v6


I have route <Route path="login" element={} />, how can I use this route in all routes: /main:page, /main/post:id. For example, when I visit /main/post:id, I want to see the PostCurrent component and the SignIn component on the same page. I guess I'm explaining my problem correctly. I'm using v6 of react-router.

   <Routes>
    <Route path="/main" element={<Main />}>
      <Route path=":page" element={<><PostList /><Pagination /></>} />
      <Route path="post/:id" element={<PostCurrent />} />
      <Route path="login" element={<SignIn />} />
    </Route>
    <Route element={<ProtectedRoute />}>
      <Route path="/dashboard" element={<Dashboard />}>
        <Route path="post-form" element={<PostForm />} />
        <Route path="post-list" element={<PostListDashBoard />} />
      </Route>
    </Route>
    <Route path="*" element={<Navigate to="/main/0" replace />} />
  </Routes>

Solution

  • If you want to render both the SignIn component on both the "/:page" and "/post/:id" routes then create a layout route to render SignIn and an Outlet for the nested Route components.

    Example:

    import { Outlet } from 'react-router-dom';
    
    const MainLayout = () => (
      <>
        <Outlet />
        <SignIn />
      </>
    );
    

    ...

    <Routes>
      <Route path="/main" element={<Main />}>
    
        // Layout route rendering Signin w/ nested routes
        <Route element={<MainLayout />}>
          <Route
            path=":page"
            element={<><PostList /><Pagination /></>}
          />
          <Route path="post/:id" element={<PostCurrent />} />
        </Route>
    
        <Route path="login" element={<SignIn />} />
      </Route>
    
      <Route element={<ProtectedRoute />}>
        <Route path="/dashboard" element={<Dashboard />}>
          <Route path="post-form" element={<PostForm />} />
          <Route path="post-list" element={<PostListDashBoard />} />
        </Route>
      </Route>
      <Route path="*" element={<Navigate to="/main/0" replace />} />
    </Routes>