Borislav Hadzhiev
Last updated: Apr 19, 2022
Check out my new book
Use the window.location.replace()
method to redirect to an external url in
React, e.g. window.location.replace('https://google.com')
. If a certain
condition is met, you can programmatically replace the current resource with the
provided URL by calling the replace()
method.
import {BrowserRouter as Router, Link, Route, Routes} from 'react-router-dom'; export default function App() { return ( <Router> <div> <Link to="/about">About</Link> <br /> <br /> {/* 👇️ If you need to simply link to external URL */} <a href="https://google.com" target="_blank" rel="noreferrer"> Google.com </a> </div> <Routes> <Route path="/about" element={<About />} /> </Routes> </Router> ); } function About() { // 👇️ redirect to external URL window.location.replace('https://google.com'); return null; }
The code snippet redirects to an external URL when the user navigates to the
/about
route.
This could be any other condition and can also be used in an if
statement.
You can use the location.replace() method to replace the current resources with the provided URL.
replace()
method, the current page will not be saved in session history.In other words, the user won't be able to use the back button to navigate to it.
We want to avoid this behavior because if the user navigates back to the
/about
route, they would get redirected to google.com
again and they
wouldn't be able to use the back button functionality.
If you want to enable the user to go back to the page that redirected them, use
window.location.href
instead of window.location.replace
.
import {BrowserRouter as Router, Link, Route, Routes} from 'react-router-dom'; export default function App() { return ( <Router> <div> <Link to="/about">About</Link> <br /> <br /> {/* 👇️ If you need to simply link to external URL */} <a href="https://google.com" target="_blank" rel="noreferrer"> Google.com </a> </div> <br /> <Routes> <Route path="/about" element={<About />} /> </Routes> </Router> ); } function About() { // 👇️ using window.location.href 👇️ window.location.href = 'https://google.com'; return null; }
Using window.location.href
instead of window.location.replace
is different
because it allows the user to go back to the route that redirected them.
In this particular case if the user clicks back, they would get redirected to
google
again.
Note that if you need to simply link to an external URL, you can use an <a>
tag.
export default function App() { return ( <a href="https://google.com" target="_blank" rel="noreferrer"> Google.com </a> ); }
The react router Link
component is intended to only be used for internal
navigation.
When the target
attribute on the a
element is set to _blank
, the external
link is opened in a new tab. You can remove the attribute if you want to open
the external URL in the same tab.