Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router switch does not mount same component for different routes

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

like image 374
Leo Teng Avatar asked Jun 17 '26 18:06

Leo Teng


1 Answers

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>
like image 180
haustraliaer Avatar answered Jun 20 '26 01:06

haustraliaer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!