I cannot comprehend how to use React Router properly. I want a component, rendered at the root (/
) to have multiple routes and redirect to /projects
by default. Routes that I want to have are these:
/projects
/projects/project/:projectId/
/projects/project/:projectId/device/:deviceId/
/projects/project/:projectId/device/:deviceId/task/:taskId/
Anyway, whatever I try, I cannot render anything past the second route despite link href matching the route path.
In a sense, I do not really want to have nested routes (at least not in the way they are implemented here, just replace components according to path instead of appending.
Here is CodeSandbox link with one of many attempts.
Here are my routes:
<Switch>
<Redirect exact from="/" to="/projects/" />
<Route path="/projects/" exact>
<p> List of projects. </p>
<Link to="/projects/project/1/"> Project #1 </Link>
</Route>
<Route path="/projects/project/:projectId/">
<p> List of devices </p>
<Link to="/projects/project/1/device/1/"> Device #1 </Link>
</Route>
<Route path="/projects/project/:projectId/device/:deviceId/">
<p> List of tasks </p>
<Link to="/projects/project/1/device/1/task/1/"> Task #1 </Link>
</Route>
<Route path="/projects/project/:projectId/device/:deviceId/task/:taskId/">
<p> Task info. </p>
</Route>
</Switch>
CodePudding user response:
This can be solved by adding exact
to the other routes.
Updated working Codesandbox
The reason for this is /projects/project/:projectId/
is the first matching route, even for a list of tasks because of the wildcard :projectId
.
<Route exact path="/projects/project/:projectId/">
<p> List of devices </p>
<Link to="/projects/project/1/device/1/"> Device #1 </Link>
</Route>
<Route exact path="/projects/project/:projectId/device/:deviceId/">
<p> List of tasks </p>
<Link to="/projects/project/1/device/1/task/1/"> Task #1 </Link>
</Route>
<Route exact path="/projects/project/:projectId/device/:deviceId/task/:taskId/">
<p> Task info. </p>
</Route>