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

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


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