Giraphi
Giraphi

Reputation: 1651

React Router v6 - Handle both external hrefs and interal paths

In my react app with react-router v6 I am retrieving links dynamically that can be either a regular external url (like https://stackoverflow.com/) or an internal path (like "/my-page") that corresponds to a Route with react-router.

So far, when using react-router-dom's <Link> component, I could only get it to work with an internal path, but NOT with an external url. As far as I understood the docs I couldn't find a way to achieve this, at least not with v6.

So the best approach I've come up with so far is to write an own MyLink component that either render an <a> or a <Link> depending on whether the href is external or not:

function MyLink(props) {
  const isHrefExternal = props.href.match(/^http|^https|^www/);

  if (isHrefExternal) {
    return <a href={props.href}>{props.children}</a>;
  }

  return <Link to={props.href}>{props.children}</Link>;
}

This of course doesn't look like a very good solution:

For a full example see this codesandbox

Can you tell me how to do it better? Ideally there would be an option to pass an external url to react-router-dom's <Link> component but I couldn't find one.

Thanks a lot!

Upvotes: 2

Views: 793

Answers (1)

Drew Reese
Drew Reese

Reputation: 202731

The Link component handles only internal links within your app, and likely won't ever handle external links natively.

I don't see any overt issues with your code, and I don't think it's a bad solution. The "isExternal" check may be naive, but it only needs to cover your specific use cases. As new use cases are required you can tweak the logic for this check. In my projects I've worked with we've just typically included an isExternal type property with fetched data so the app doesn't even need to think about what is or isn't an external link, it just checks the flag when rendering.

Upvotes: 1

Related Questions