Search code examples
javascriptreactjsreact-routerreact-component

React router nested routes with exact path


Please help. I'm trying to make nested routes but here is a problem: if I use exact path, I can't have nested routes.

For example, I want to have one route that is nested and one individual. I have to use exact if I want to have an individual one. How can I have both?

  <Route exact path="/projects" component={Projects} />

  <Route path="/projects/individual" component={ProjectsList} />
  <Route path="/projects/nested" component={ProjectsList} />

Here is codesandbox.


Solution

  • You are right, with an exact attribute you loose the flexibility to use nested routes. The solution here is to make use of Switch and order your routes such that the prefix paths are at the end

    <Switch>
      <Route path="/projects" component={Projects} />
      <Route path="/" component={Home} />
    </Switch>
    

    and inside Projects you can write the nested paths

    <Route path="/projects/individual" component={ProjectsList} />
    <Route path="/projects/nested" component={ProjectsList} />
    

    Update:

    If however on ProjectsList component i.e paths "/projects/individual" and "/projects/nested" you do not want to render Projects component you would use them like

    <Switch>
      <Route path="/projects/individual" component={ProjectsList} />
      <Route path="/projects/nested" component={ProjectsList} />
      <Route path="/projects" component={Projects} />
      <Route path="/" component={Home} />
    </Switch>