I want to use an anchor tag in my react spa (using react-router). But if I give it, for example, an href
value of google.com
, it will just extend my spa route, to say myreactspa.com/sampleRoute/google.com
. Is there any way to make my anchor tag directly link to google.com? Or must I append, for example, https://
to my href
value? Thanks!
![](../../users/profiles/7460467.webp)
- 1,580
- 2
- 23
- 55
-
1Seems to have been answered [here.](https://stackoverflow.com/questions/42914666/react-router-external-link) – Jack Strosahl Jul 26 '19 at 16:39
-
1Possible duplicate of [React-Router External link](https://stackoverflow.com/questions/42914666/react-router-external-link) – Jack Strosahl Jul 26 '19 at 16:40
3 Answers
Use Route
component rendering null
and change the window's location.
<Route path='/externalresource' component={() => {
window.location.href = 'http://google.com'
return null
}}/>
![](../../users/profiles/10106580.webp)
- 15,944
- 5
- 23
- 43
You should append https://
to your URL and set the target
attribute of the a
tag to _blank
. It is not a problem of React Router to handle external links.
So something like that:
<a href="https://www.google.com target="_blank">Link</a>
There is no need to try use React Router to handle external links
![](../../users/profiles/8534482.webp)
- 2,273
- 1
- 5
- 13
react-router (and similar) is specially designed for SPA. When you are trying to navigate to another website (external link), the router is not supposed to handle that. If you are using Link
, then whatever path you pass, react-router assumes that to be a route of your SPA (this is expected behaviour, NOT a bug).
If you want to navigate to another website from your web-app, use plain anchor tag like this
<a href="website_link">Click here</a>
If you want to open the page in a new tab use
<a href="website_link" target="_blank" rel="noopener noreferrer">Click here</a>
![](../../users/profiles/11608609.webp)
- 114
- 8