Cannot render same route with different parameters react router v4

Viewed 4242

I am implementing a react page with route info/:id. From this page, there are various URLs which are navigated by NavLink.

For example: if current route is localhost:3000/info/1 and there are links localhost:3000/info/2 and localhost:3000/info/3, clicking on those links will load the page I'm currently on i.e: localhost:3000/info/1. While tracking for props changes, url is getting changed briefly but it's again loading the same page. What shall I do to route to same component with different parameters?

Thanks in advance!!!!!!

2 Answers

You should track your page updates in componentDidUpdate lifecycle method or useEffect hook.

Class components:

 componentDidUpdate(prevProps) {
   if(prevProps.match.params.id !== this.props.match.params.id){
     // do something
   }
 }

Functional components:

useEffect(() => {
    // do something
}, [props.match.params.id]);

Here's how you achieve same via React hooks and functional components:

useEffect(() => {
    //do something
}, [props.match.params.id]);
Related