Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having issues using React Router 5

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:

  1. /projects
  2. /projects/project/:projectId/
  3. /projects/project/:projectId/device/:deviceId/
  4. /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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading