Home > Software design >  DOM does not render when adding a nested route in react router. Why would this be happening?
DOM does not render when adding a nested route in react router. Why would this be happening?

Time:11-14

I'm trying to add a nested route that will render along with it's parent route to my app, but when I add the nested route, the whole document disappears. Why is this happening? My code looks somewhat like this:

import React from "react"
import {BrowserRouter, Routes, Route, Outlet} from "react-router-dom"

function Foo(){
  return(
    <div>
      <h1>This is the parent</h1>
      <Outlet />
    </div>
  )
}

function Child(){
  return(
    <div>
      <p>This is the nested route</p>
    </div>
  )
}

function App(){
  return(
    <div>
      <BrowserRouter>
        <Routes>
          <Route path='/parent' element={<Foo />}>
            <Route path='/' element={<Child />}/>
          </Route>
          {/*Additional Routes and stuff*/}
        </Routes>
      </BrowserRouter>
    </div>
  )
}

When I run this, the DOM does not render. I get an entirely blank page for all routes. When I delete the line <Route path='/' element={<Child />}/> everything renders just fine. What is wrong with this line that prevents everything else from rendering?

Edit: I solved the problem, but I don;t understand why this solved the issue.

So in the line <Route path='/' element={<Child />}/> I deleted the "/" character from the path element by accident, making it just <Route path='' element={<Child />}/>. Now, the DOM renders without any issues. Can somebody explain to me, why this worked? All the guides that I've been using for React Router use the "/" character in the path element.

CodePudding user response:

The nested route's path is built relative to the parent's path, so nesting absolute path "/" under "/parent" is invalid. path="" is effectively like not specifying a path at all, so the route matches and renders. If you want a child route to render on the same path as the parent component then specify that it is an index route using the index prop.

Example:

function App(){
  return(
    <div>
      <BrowserRouter>
        <Routes>
          <Route path='/parent' element={<Foo />}>
            <Route
              index // <-- matches on `"/parent"`
              element={<Child />}
            />
          </Route>
          {/*Additional Routes and stuff*/}
        </Routes>
      </BrowserRouter>
    </div>
  )
}
  • Related