17

i have used react router doms' Link:

<Link target="_blank" to={"www.mylink.com"} >mylink </Link>

but this would open new tab to http://localhost:3000/www.mylink.com also, using a href:

<a href={'www.mylink.com'} target="_blank" > mylink </a>

does the same. opens new tab to http://localhost:3000/www.mylink.com how do i open in new tab only the link?

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

3 Answers3

22

try this

<Link target="_blank" to={"//www.mylink.com"} >mylink </Link>

or this

<a href={'//www.mylink.com'} target="_blank" > mylink </a>

for more reference:
Absolute vs relative URLs
https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax

am05mhz
  • 2,727
  • 2
  • 23
  • 37
  • This is brilliant. It helped me as well. Does anybody know, why is this the answer? I was trying to find in the docs but could not find it... – Lazar Nikolic Sep 21 '18 at 10:20
  • 2
    @lazar this is actually have a lot to do with how modern browsers works, not actually react problem. It is known that browsers would prepend the domain you are visiting to links that does not start with http:// or https:// or other protocols. This create problem when you have to specify explicitly http or https, thus modern browsers support the // to indicate that the browser does not need to prepend current domain – am05mhz Sep 22 '18 at 12:13
  • @am05mhz Thanks! – Lazar Nikolic Sep 22 '18 at 15:31
  • 1
    if your using variables ```link``` – U.A Jun 16 '19 at 17:18
  • anyone please tell my why not do ` mylink ` instead? – Kai May 13 '20 at 18:36
  • you can read the link attached in the answer, relative vs absolute url, start with `/` means url is directly after domain, `//` means its on another domain, without both is relative to current url path, next time please read thoroughly – am05mhz May 14 '20 at 04:14
1

I tried to use Link but I had the same problem. Now I'm using this onClick={() => { window.open('LINK','_blank')}}

0

When I used Link like

<Link to={`//${isHrefVlaue}`}></Link>

this was opening without localhost, but it was missing the colon in https and not working as expected.

But then it worked after I replaced Link with an anchor like

<a href={isHrefVlaue}></a>
tdy
  • 36,675
  • 19
  • 86
  • 83