Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using same component for different route path in react-router v4

People also ask

How do I render the same component on different routes?

To match multiple path names for a same component in React Router, we can make changes according to the React Route version we're using. If we're using React Router v4, we set the path prop to an array of paths to match. to set the path prop to ["/home", "/users", "/widgets"] to match all of the routes listed.

Does react router allows for nested routes?

With React Router, you have two options for creating nested routes. The first is using the /* with nested <Routes> pattern and the second is using the <Outlet /> pattern.


Using different key for each route should force components to rebuild:

    <Route 
      key="add-client"
      exact path="/add-client"
      component={manageClient} 
    />

    <Route 
      key="edit-client"
      exact path="/edit-client"
      component={manageClient} 
    />

One solution is use inline function with component, that will render a new component each time, But this is not a good idea.

Like this:

<Route exact path="/add-client" component={props => <ManageClient {...props} />}></Route>
<Route exact path="/edit-client" component={props => <ManageClient {...props} />}></Route> 

Better solution would be, use componentWillReceiveProps lifecycle method in ManageClient component. Idea is whenever we render same component for two routes and switching between them, then react will not unmount-mount component, it will basically update the component only. So if you are making any api call or require some data do all in this method on route change.

To check, use this code and see it will get called on route change.

componentWillReceiveProps(nextProps){
   console.log('route chnaged')
}

Note: Put the condition and make the api call only when route changes.


<Route exact path={["/add-client", "/edit-client"]}>
  <manageClient />
</Route>

Reference

Version 5.2.0

https://reacttraining.com/react-router/web/api/Route/path-string-string