Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change Url when component renders with react-router-dom?

Is there a way in react router that whenever some components renders the url changes accordingly.

One way which I know is to place window.history.pushState('', '', '/componentUrl'); in the render function of the component

Is there any better way to accomplish it within the route other than path props in Route because path= 'someurl' means whenever someurl is accessed someComponent should render

But in the other way round whenever someComponent renders urls should change to someurl I'm taking this senerio in context of conditional rendering inside a component.

like image 338
ashwintastic Avatar asked Aug 16 '17 07:08

ashwintastic


1 Answers

The most important thing to know when using react-router is that:

The path attribute defines the route URL and component attribute defines the component for this route.

I would suggest having a read through this. Best practice suggest, just like Matt Derrick suggested in the comments that the URL should drive the rendering of components.

Since you have Acomponent and Bcomponent that render based on the state I would suggest you then have 2 different URLs to accompany that. So when state changes to be ==='a' then you will jump to /aURL, when the state changes to be ==='b' then you will jump to /bURL.

Hope this answers your question.

like image 137
Dragomir Kolev Avatar answered Oct 07 '22 19:10

Dragomir Kolev