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
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