Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router v4 nested routes & programmatic navigation

So, I have a few routes set up in this fashion:

index.js

<Route exact path={pathDefault} component={Home}>
    <Route path={path1} component={component1}/>
    <Route path={path2} component={component2}/>
</Route>

component1.js

<Route exact path={`${props.match.url}`} component={Summary}/>
<Route path={`${props.match.url}`/someOtherPath1} component={SubComponent1}/>
<Route path={`${props.match.url}`/someOtherPath2} component={SubComponent2}/>

component2.js is set up similarly.

The idea here is that I have multiple top-level routes, which have default pages. But, then sub-routes that can be switched between. This works ok, until, when at one of the sub-level routes like component1/someOtherPath2 I can switch between someOtherPath1 and someOtherPath2, but if I then try to change one of the top level routes using history.push(path2), instead of going back to a top level component (i.e. path1's default component), it ends up pushing a compounded, and thus incorrect route, like component1/component2.

So, how would you change a higher-level route when in a lower level component programmatically (preferably using history.push or similar)?

like image 915
Araymer Avatar asked Dec 02 '25 21:12

Araymer


1 Answers

history.push takes path as an argument and not component:

history.push(path, [state])

for example:

history.push('/home');

or

history.push('/home', { some: 'state' });

you can read more about it in the docs.

EDIT:

also don't forget the leading / if you want to change the root path. For example:

history.push('/path1/path2');
like image 97
patotoma Avatar answered Dec 05 '25 09:12

patotoma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!