skip to Main Content

I’m trying to implement nested routing in a react app, using this code:

  <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="plans" element={<Plans />} />
        <Route path="trainers" element={<Trainers />} />
        <Route path="store" element={<StoreMain />} />
        <Route path="myportal" element={<MyPortal />}>
          <Route path="workouts" element={<WorkoutsFetch />} />
        </Route>
        <Route path="login" element={<Login />} />
        <Route path="signup" element={<Signup />} />
      </Routes>
    </>

In the MyPortal component there is a link where it leads the user to workouts component. This component renders a div, which contains fetched data. The components itself works flawlessly, but the part that doesn’t work is when I try to go to that route – it doesn’t render anything. The URL changes to /myportal/workouts, but the pages doesn’t updates. Any suggestions?

I looked into other Stack Overflow solutions where I tried to do this:

<Route path="myportal/*" element={<MyPortal />}> // - with /* after the path
  <Route path="workouts" element={<WorkoutsFetch />} />
</Route>

But this didn’t help my problem.

2

Answers


  1. Since your route is a child of myportal, you’ll need to index it, putting it as:
    <Route index element={} /> should resolve your issue.

    Make sure you also have an outlet in the parent: https://reactrouter.com/en/main/components/outlet

    Login or Signup to reply.
  2. You have to wrap it in BrowserRouter

    <BrowserRouter>
    
    <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="plans" element={<Plans />} />
        <Route path="trainers" element={<Trainers />} />
        <Route path="store" element={<StoreMain />} />
        <Route path="myportal" element={<MyPortal />}>
          <Route path="workouts" element={<WorkoutsFetch />} />
        </Route>
        <Route path="login" element={<Login />} />
        <Route path="signup" element={<Signup />} />
      </Routes>
    
    </BrowserRouter>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search