Discover how to use React Router to link to an external URL, thanks to the Link component or an HTML anchor tag (<a>
).
How to Add an External Link With React Router?
You can use the Link
component or an HTML anchor tag if you want to redirect to an external link with React Router. Using the <Link>
component, you can do it thanks to the pathname
and target
parameters. It will redirect the user to the specified URL.
Using React Router
In React, React Router is the most used library to manage your application routing (multi-pages application). Thanks to a set of functions and components provided by them, you can build a lot of features.
If you use this library to redirect to an external URL, you can use the <Link />
component with the pathname
and target
property.
Let’s discover how to open the HereWeCode homepage in a new tab:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom"
import "./styles.css";
export default function App() {
return (
<Router>
<Switch>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
)
}
function Home() {
return (
<div>
<Link to={{ pathname: "https://herewecode.io/" }} target="_blank">Click to open HereWeCode (new tab)</Link>
</div>
)
}
As you can see above, when you pass an external URL to the React Router Link
component and combine it with a target="_blank"
property, the link will open a new tab with the URL of your choice.
Note: Unfortunately, it's impossible to open an external URL in the same tab using React Router. If you don't provide the target property, the router will append the URL to your current website URL (e.g.,
https://my-website.com/https://herewecode.io/
). In the next section, I'll show you how to open an external link in the current tab.
Using an Anchor Tag ()
If you want to open an external link to the current tab, the most straightforward way is to use the native anchor tag in HTML (<a>
).
Here’s how to do it:
import React from "react"
export default function App() {
return (
<div>
<p>
<a href="https://herewecode.io/">
Click to open HereWeCode (current tab)
</a>
</p>
<p>
<a href="https://herewecode.io/" target="_blank">
Click to open HereWeCode (new tab)
</a>
</p>
</div>
)
}
As you notice, we pass the external link to the href
property. If no target="_blank"
property is given, the link will open in the current tab; otherwise, in a new tab.
If you want to learn more about React, here’s an article on how to get URL params in React (with React Router V5/V6 and without).
Thanks for reading. Let’s connect!
➡️ I help you grow into Web Development, and I share my journey as a Nomad Software Engineer. Join me on Twitter for more. 🚀🎒