How to route correctly with a mixture of parent and child routes with React Router

Viewed 94

I'm trying to play around with Reacter-Router, but running into issues when I start introducing some child routes, and getting them to then route back to the parent routes.

I've attached a CodeSandbox link below which contains the current code, if anyone can see where I'm going wrong?

What I'm trying to do is to have a set of parent and child routes, and allow routing from parent --> child & from child --> parent. You'll see in the example that the child routes do not work, but if you navigate straight to higher_level_route, it works.

https://codesandbox.io/s/compassionate-tdd-ynqdc?file=/example.js

2 Answers

There are 3 problems here.

1 - As already explained, remove exact prop as it prevents the rendering of CoreComponent.

2 - change path ${path}/one to ${path}one in all the Route in CoreComponent. You can log both path and url to see what value actually it holds. In your current situation, the value of path is //one and the value of link is /one. So removing a slash makes everything work as expected.

3 - You need to change the order of route in the RoutingApp component. Since Switch always render only one route(i.e the 1st match), you need to place /higher_level_route first and then the '/'.

<Router basename="/base/path">
  <Switch>
    <Route path="/higher_level_route">
       <HigherLevelComponent />
    </Route>
    <Route path="/">
       <CoreComponent />
    </Route>
  </Switch>
</Router>

I hope it helps now.

Related