Pages are merging for Reactjs routing?

Viewed 253

I have an issue while routing path of reactjs application.I need two exact paths

1.  path = /user/
2. path = /user/setting

When i call the second path its shows a merged page of both components

   <Route path='/user/:param1'   component={routeProps => <MyTab {...routeProps} remotes={remotes} />}/>
    <Route path='/(user/settings)/:param1'   component={UserSettings}/>
2 Answers

You can write the routes wrapped by a switch component and reorder them so that the first matching route is rendered

<Switch>
    <Route path='/(user/settings)/:param1'   component={UserSettings}/>
    <Route path='/user/:param1'   component={routeProps => <MyTab {...routeProps} remotes={remotes} />}/>
</Switch>

The reason you see the current behaviour is because '/(user/settings)/:param1' also matches '/user/:param1' where params will be settings as we aren't checking for an exact match and hence both routes are rendered

Reordering the routes within Switch will make sure that if /user/settings/:param1 matches the rest routes are not matched. If you do not re-order, the '/user/:param1' route will get matched for /user/settings/:param1 and the UserSettings component will never be rendered

You could simply use exact keyword on both the routes like

<Route exact path='/user/:param1'   component={routeProps => <MyTab {...routeProps} remotes={remotes} />}/>
<Route exact path='/(user/settings)/:param1'   component={UserSettings}/>

However if you do that, you won't be able to write any nested routes within MyTab or UserSettings component

As Shubham has explained, the /(user/settings)/:param1 path is matching /user/:param1. What you can do is to add the exact props, which sets it to true.

<Route exact path='/user/:param1'   component={routeProps => <MyTab {...routeProps} remotes={remotes} />}/>
<Route exact path='/(user/settings)/:param1'   component={UserSettings}/>

This disables the partial matching for the route, ensuring that it returns the route if the path exactly matches.

Related