React Router: Wrapping some Routes with a component and not directly inside Switch

Viewed 799

I'm trying to do something like this

<Switch>
    <SomeNavBar>
        <Route path="page1">Page 1</Route>
        <Route path="page2">Page 2</Route>
        <Route path="page3">Page 3</Route>
    </SomeNavBar>
    <OtherNavBar>
        <Route path="admin">Admin Page</Route>
    </OtherNavBar>
</Switch>

Where I have wrapper component for a routes that are not the admin page.

However the admin route does not render Admin Page it just renders a blank page. The other routes work fine.

Is there a way to achieve this behavior?

1 Answers

There's a couple of issues with your example not related to the question which you should rectify before anything else.

The first is that the direct children of a Switch must always be a Route or Redirect - it doesn't know what to do with any other element and will just render the first thing it sees (in your case, the SomeNavBar component). The second is that path declarations must be prepended with a slash for the router to build them correctly, so /page1 and /admin for example.

With that out the way, here is a somewhat contrived example of how to get the behaviour you are after. For the pages, we are checking from a list of possible fragments before rendering SomeNavBar and the correct route. Notice also the exact parameter - this is so we don't also match paths that only begin with the specificed fragment, like /page1foo:

<Switch>
  <Route exact path={['/page1', '/page2', '/page3']}>
    <SomeNavBar>
        <Route path="/page1">Page 1</Route>
        <Route path="/page2">Page 2</Route>
        <Route path="/page3">Page 3</Route>
    </SomeNavBar>
  </Route>
  <Route path="/admin">
    <OtherNavBar>
      Admin Page
    </OtherNavBar>
  </Route>
</Switch>
Related