Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling React Router from vanilla JS

I have a react single page application using React Router, and having paths defined using Link as shown below:

 <Link to="second" className="level-2" params={{id:item.content}} title={item.name}>{item.name}<br/></Link>

This changes url from /myapp/firsturi to /myapp/seconduri

Is it possible for me to make the same react router action using vanilla JS? I tried using history.pushState() and history.replaceState() but while the url updates correctly, the content on the page does not. I can get the same thing using window.location.href="/myapp/seconduri" but that causes a page refresh which is not what I want.

Any idea how to go about this?

like image 226
navinpai Avatar asked Dec 01 '25 09:12

navinpai


2 Answers

This has worked for me:

// simulate navigation to where you want to be (changes URL but doesn't navigate)
window.history.pushState("","","/url");
// simulate navigation again so that
window.history.pushState("","","/url");
// when you simulate back, the router tries to get BACK to "/url"
window.history.go(-1);

Everything else I tried was just forcing the DOM to reload again as if it was a link click.

like image 90
ASomN Avatar answered Dec 03 '25 21:12

ASomN


React Router relies on the history module to handle locations. When the page loads it parses the initial URL, which is why setting window.location.href works.

The history that you use includes a listen function which React Router uses to listen for location changes. When one occurs, it will trigger a re-matching of the new location against your routes, which in turn will render the correct components.

Manually calling pushState/replaceState does not trigger the listening function, which is why your app is failing to update. Instead, you should use your history instance to navigate.

like image 23
Paul S Avatar answered Dec 03 '25 23:12

Paul S



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!