Jonas
Jonas

Reputation: 7935

Link in nested Router can't navigate to a route of the parent Router

I have a nested router but my nested Router can't route to a route of the parent Router.

The Link in the nested Router does not work. It shows /admin in the url but does not route to the AdminPage. When I reload the page it works. The not nested Link to the AdminPage works as expected.

So how can I have a Link that routes to a route of the parent Router?

This is my code:

function App() {

  return <BrowserRouter>
      <div>
          <nav>
              <ul>
                  <li>
                      <Link to={`/admin`}>Admin</Link>    <-- does work
                  </li>
                  <li>
                      <Link to={`/`}>School</Link>
                  </li>
              </ul>
          </nav>
      </div>
      <Switch>
          <Route path="/admin">
              <AdminPage></AdminPage>
          </Route>
          <Route exact path={"/"}>
              <BrowserRouter>
                  <div>
                      <nav>
                          <ul>
                              <li>
                                  <Link to="/">Home</Link>
                              </li>
                              <li>
                                  <Link to="/profile">Profile</Link>
                              </li>
                              <li>
                                  <Link to="/admin">Admin</Link>    <-- does not work
                              </li>
                          </ul>
                      </nav>
                  </div>
                  <Switch>
                      <Route path="/profile">
                          <h1>Profile</h1>
                      </Route>
                      <Route exact path="/">
                          <h1>Home Page</h1>
                      </Route>
                  </Switch>
              </BrowserRouter>
          </Route>
      </Switch>
  </BrowserRouter>
}

export default App;

Upvotes: 1

Views: 57

Answers (1)

ian
ian

Reputation: 1181

Why do you have a second <BrowserRouter>?

As far as I am aware you can just nest <Route> within each other. The <BrowserRouter> is only needed once around all the routes. In your example you don't even need to nest anything.

Also see the docs to react router nesting

Upvotes: 1

Related Questions