Reputation: 1651
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:
isHrefExternal
is very naiveMyLink
should accept and how they should be managed since <a>
and <Link>
have different props.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
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