Olufuwa David
Olufuwa David

Reputation: 53

Rendering a Nested route in React router v6 on a different page

function App() {
  return (
    <Router>
        <Routes>
          <Route path='/' element={<Home/>}/>
          <Route path='doctor' element={<Doctor/>} >
            <Route path='/home' element={<Homepage/>}/>
          </Route>
          <Route path='admin' element={<Admin/>}/>
        </Routes>
    </Router>
  );
}

Please how do I ensure that the nested route '/homepage' renders on a new page instead of within the doctor route

Upvotes: 2

Views: 563

Answers (1)

Drew Reese
Drew Reese

Reputation: 202721

If you are wanting to render Homepage on its own page separate from the Doctor component then it'll need to be its own separate route. You can do this a couple ways.

Unnested route on its own absolute path.

function App() {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/doctor' element={<Doctor />} />
        <Route path='/doctor/home' element={<Homepage/>} />
        <Route path='admin' element={<Admin />} />
      </Routes>
    </Router>
  );
}

Nested on its own relative path as a sibling to a route rendering Doctor.

function App() {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/doctor'>
          <Route index element={<Doctor />} />        // <-- "/doctor"
          <Route path='home' element={<Homepage/>} /> // <-- "/doctor/home"
        </Route>
        <Route path='admin' element={<Admin />} />
      </Routes>
    </Router>
  );
}

Upvotes: 1

Related Questions