4

I have two components that both have a switch element like so:

function App() {
  return (
    <div className="App">
    <Router>
        <AppBar position="static" color="inherit">
          <Toolbar>
            <Button color="inherit"><Link to="/deployments">Deployments</Link></Button>
            <Button color="inherit"><Link to="/tasks">Tasks</Link></Button>
          </Toolbar>
        </AppBar>
        <Switch>
          <Route exact path="/tasks" component={TasksPage}>
          </Route>
        </Switch>
    </Router>
    </div>
  );
}
function TasksPage({match}) {
    return (
        <div className="DeploymentsPage">
          {loading ? <h1>Loading...</h1> : 
          <div>
            <h1>Available Tasks</h1>
            <ul>
              {tasks.map((el, i) => <li key={i}><Link to={`${match.path}/${el.id}`}>{el.id}</Link></li>)}
            </ul>
            </div>
          }
         <Switch>
          <Route exact path="/tasks/:id" component={TaskPage} />
         </Switch> 
        </div>
    );
}

If I go to /tasks/1 now, the TaskPage is not shown! Whereas if I move the exact same Route element into the Switch of App it works just fine.

Why is that? I tried to follow this tutorial: https://reacttraining.com/react-router/web/guides/quick-start

isherwood
  • 58,414
  • 16
  • 114
  • 157
Jonathan R
  • 3,652
  • 3
  • 22
  • 40

2 Answers2

17

To add more information about @Miller comment, because you add exact to your main Route (/tasks), your nested Route (/tasks/:id) can never be reached.

Example : If you attempt to have exactly /tasks, you can't hit this route with /tasks/1.

See how exact works here

It should work without the exact on your main Route.

Similar example of what you want to achieve : https://v5.reactrouter.com/web/example/route-config

Darkilen
  • 571
  • 4
  • 18
-3

I think you are misunderstanding the concept of Switch statements and Routes. ( https://reacttraining.com/react-router/web/guides/quick-start )

Nevertheless, you should declare all your routes directly into App.js, for instance. And, if you want to redirect the user for certain route, just use NavLink. Moreover, you cannot nest Switches!!! You might as well just nest Routes.

Thus, this might be the reason for all your troubles. Try creating a nested Route instead.

This link might help you better in the visual part:

React Router v4 Nested Routes with Switch

https://github.com/ReactTraining/react-router/issues/6199 << supreme!