No Time to Read - Copy/Paste - Simulate Link Click
If you want to redirect to another URL but keep the original URL in the browser's history (i.e. as if someone clicked on a link)
function redirect (url) {return window.location.assign(url)}
No Time to Read - Copy/Paste - Replace History
If you want to redirect to another URL and replace the original URL in the browser's history (i.e. when the user clicks the "back" button, they won't be taken to the original page)
function redirect (url) {return window.location.replace(url)}
No Time to Read - Copy/Paste - Change Path
If you want to redirect to another page on the same site (i.e. /settings to /dashboard)
function changePath (path) {return window.location.pathname = path}
Explained
We first learned about the location
object when we learned how to get the current url in JavaScript. Now instead of getting the current URL, we want to redirect to another page. As you can see above, the location
object can help us with this as well.
The biggest question you need to answer is in regards to how you want to redirect. If you want to simulate a user clicking on an anchor tag, i.e.
<a href={url}>Click Me</a>
Then you'll want to use window.location.assign(newURL)
. If you use window.location.assign
and the user clicks the "back" button, they'll be taken back to the page they just came from (just like they clicked on a normal anchor tag). However, if you want to replace the user's current session, meaning when they click the back button they won't be taken to the page they just came from, you'll want to use window.location.replace(newURL)
.
window.location.assign
Site Aclicks <a> to Site BSite Bwindow.location.assign('C')Site Cclicks "back" buttonSite B
window.location.replace
Site Aclicks <a> to Site BSite Bwindow.location.replace('C')Site Cclicks "back" buttonSite A
Now what if instead of redirecting to a new site, you wanted to redirect to a different page on the same site. Something like Home Page (/) to Dashboard (/dashboard). To do this, you'd need to reassign window.location.pathname
to whatever the new path you wanted to go to was.
Page /aclicks <a> to Page /bPage /bwindow.location.pathname = 'c'Page /c