3

I have these routes defined

<Switch>
    <Route path='/1' render={() => <ComponentA />} /> 
    <Route path='/2' render={() => <ComponentA />} />
    <Route path='/3' render={() => <ComponentA />} />
</Switch>

When I hit the app on page on /1, ComponentA renders fine. But when I navigate to /2, ComponentA doesn't get remounted but the render function does fire.

If I use a different component, it will get mounted properly

ComponentA changes what to render base on props and the action to retrieve data is fired in componentDidMount

Is this the intended behavior, it would seem like that we are not suppose to reuse component for different routes

Leo Teng
  • 93
  • 5
  • Just curious, why you would like to render the the same component in different `routes`? Modifying the `props` or `state` can just changes the component. – Hearen Mar 30 '18 at 02:01
  • It's an interesting question. Though I don't know the answer to your question specifically, on a broader level, a better way of doing something like this is using a regex in path as follows: . Taken from here: https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router – raksheetbhat Mar 30 '18 at 06:28
  • Thank you guys for the comments. This is a very generic example of the problem I am facing. ComponentA is an entry level component that grabs the template externally base on routes. The only real reason I am using Switch is so I can have a default page when pages don't exist – Leo Teng Mar 30 '18 at 08:13

2 Answers2

6

Just chuck a unique key on your render components - that fixed it for me.

<Switch>
   <Route path='/1' render={() => <ComponentA key={1} />} /> 
   <Route path='/2' render={() => <ComponentA key={2} />} />
   <Route path='/3' render={() => <ComponentA key={3} />} />
</Switch>
0

There are two ways you can fix this.

  1. Use a unique key prop for each route.

<Switch>
    <Route key="key1" path='/1' render={() => <ComponentA />} /> 
    <Route key="key2" path='/2' render={() => <ComponentA />} />
    <Route key="key3" path='/3' render={() => <ComponentA />} />
</Switch>
  1. Use a key prop for each component used inside the render.

<Switch>
    <Route path='/1' render={() => <ComponentA key="key1" />} /> 
    <Route path='/2' render={() => <ComponentA key="key2" />} />
    <Route path='/3' render={() => <ComponentA key="key3" />} />
</Switch>

You can read from the official sites to know more about the keys: 1. React 2. React Router

Jaied
  • 900
  • 9
  • 13