Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External link in react is being appended with localhost if no http or https present

I'm using this code right now to open an external link from a generated URLs:

External link in react is being appended with localhost if no http or https present

  <a href={url} target={'_blank'} rel="noopener noreferrer external">
        {url}
  </a>

It's working fine if there's an http or https present inside the url but if there's none then it will be redirected to http://localhost:3000/${url}.

Is there a way to ignore this setting in React(Create React App)

like image 970
ajbee Avatar asked Nov 21 '25 17:11

ajbee


1 Answers

This is not related to react at all, this is based on how the browsers understands urls. There are 4 types of urls:

http://yourdomain.com/images/example.png: ( this works fine for you, because it is an absolute url, and the browser will open it as it is)

//yourdomain.com/images/example.png (this is also like the previous one, and will work fine for you, except the scheema here is relative to the current host, if your website is https it will open https otherwise it will open http)

You are having issues with the following two urls, and thats because these work relative to the current host, in your case it seems your website is on http://localhost:3000

/images/example.png (relative to the document root)

images/example.png (relative to the path)

now if you want to convert relative urls to be relative to another host, use the URL constructor like this

const baseOfAnotherHost = 'https://someotherdomain.com'
// can also work with relative urls like 'doc/sign/' or '/doc/sign'
const relativeOrAbsoluteURL = 'https://www.someotherdomain.com/doc'
const absoulteUrl = new URL(relativeOrAbsoluteURL,baseOfAnotherHost).href
<a href={absoulteUrl} target={'_blank'} rel="noopener noreferrer external">
    {absoulteUrl}</a>
like image 107
ehab Avatar answered Nov 24 '25 06:11

ehab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!