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

beNerd picture beNerd · Feb 27, 2018 · Viewed 13k times · Source

I am trying to have separate routes but same component for add/edit forms in my react app like the below:

<Switch>
        <Route exact path="/dashboard" component={Dashboard}></Route>
        <Route exact path="/clients" component={Clients}></Route>
        <Route exact path="/add-client" component={manageClient}></Route>
        <Route exact path="/edit-client" component={manageClient}></Route>        
        <Route component={ NotFound } />        
</Switch>

Now in the manageClient component, I parse the query params (I pass in a query string with client id in edit route), I render conditionally based on the query param passed.

The problem is that this doesn't remount the whole component again. Say an edit page is opened, and the user clicks on add component, the URL changes, but the component doesn't reload and hence remains on the edit page.

Is there a way to handle this?

Answer

user5699040 picture user5699040 · Feb 27, 2018

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} 
    />