Home > Software engineering >  React Router dom change history without changing the component
React Router dom change history without changing the component

Time:10-22

In simple words, I need to know whether react router dom has something like History.pushState()

Detailed

I have a component which will have intial url of /home/1/1. Everytime user clicks on a button the route should change to /home/1/2, /home/1/3. And I need it to re-render according to the change in path. I can't figure it out. Now, I think History.pushState() may work, but still wondering is there any other solution, with or without react router dom

CodePudding user response:

If you want to render your component depending on the route, then doing a history.push() is the correct solution.

If you are using a functional component, then consider using the useHistory hook to retrieve the history in order to push the new route (see example), and the useParams hook to retrieve the route parameters (see example).

If you are using a class component, then you can wrap your component in the withRouter higher-order component to access the history and to retrieve the parameters (see example).

CodePudding user response:

Let's say that route of your component which needs to be re-rendered is defined like "home/1/:id" in the path attribute of Route component, For eg.

In the YourComponent, you can trap into router props and you can add that as a dependeny to the useEffect. You can use "useParams" hook as well to retrive the params object.

 const YourComponent = (routerProps) =>{

 useEffect(()=>{
  //your logic
 }, [routerProps.params.id])

}
  • Related