Re-render same component on url change in react

Ayan Banerjee picture Ayan Banerjee · Sep 10, 2018 · Viewed 9.2k times · Source

I have a route which takes an id and renders the same component for every id, for example : <Route path='/:code' component={Card}/>

Now the in the Link tag I pass in an id to the component.Now the Card component fetches additional detail based on the id passed. But the problem is it renders only for one id and is not updating if I click back and goto the next id. I searched and found out that componentsWillReceiveProps can be used but during recent versions of React it has been deprecated. So how to do this?

Answer

Saša Đurić picture Saša Đurić · Mar 27, 2020

Putting current location as key on component solves problem.

<Route path='/:code' component={(props) => <Card {...props} key={window.location.pathname}/>}/>