Search code examples
javascripthtmlreactjsjsxreact-router-dom

Inside react router componet, a tag, link is add to curr url


Inside a react-router component when I am using <a> tag with external link, the link is appended to current url of the application and routing me to there.

<a
  href={job.profileId.website}
  target="_blank"
  className="text-blue-600 hover:underline"
  rel="noopener noreferrer"
>
  {job.profileId.website}
</a>

ex: "http://127.0.0.1:5173/www.website.com"

I am using "react": "^18.2.0", "react-router-dom": "^6.11.1"

I have tried researching and asked to chatGPT, but found no solution. Maybe this is react-router error, but can be solved by any other method?


Solution

  • This isn't an issue with react-router, and react-router doesn't handle external links. The issue here is with the literal link target value being used not being a valid absolute URL. "www.website.com" is being treated as a relative path, so it's appended to the current URL, e.g. "http://127.0.0.1:5173/www.website.com".

    If you want to link to an external URL then the link target should look something more like "https://www.website.com". You can either create the valid URL path with something like href={`https://${job.profileId.website}`}:

    <a
      href={`https://${job.profileId.website}`}
      target="_blank"
      className="text-blue-600 hover:underline"
      rel="noopener noreferrer"
    >
      {job.profileId.website}
    </a>
    

    or update the job.profileId.website property value to be the complete absolute URL like job.profileId.website = "https://www.website.com" so href={job.profileId.website} has the link value you need.