remix-run / react-router

Declarative routing for React
https://reactrouter.com
MIT License
53.16k stars 10.31k forks source link

[Feature]: Support external links with the Link and NavLink component #8410

Closed andrelandgraf closed 2 years ago

andrelandgraf commented 2 years ago

What is the new or updated feature that you are suggesting?

Link and NavLink components should support external/outgoing links.

It would be great if the following code would work:

<Link to="https://github.com">Find us on GitHub</Link>

Internally, this could be based on a simple checkup if:

if(to.toString().startsWith('http') || to.toString().startsWith('mailto') || to.toString().startsWith('tel')) {
  // render anchor tag without client-side routing
}

or client-side also via the window object:

function isExternalLink(link: string): boolean {
  const url = new URL(link);
  return url.hostname !== window.location.hostname;
}

In case an external/outgoing link is passed to Link/NavLink, a simple anchor tag could be used.

Why should this feature be included?

Currently, if you want to use a unified Link component in your React app, you have to create a wrapper component around Link/NavLink and pass it some property such as isExternal to then either render an anchor or a react-router-dom Link/NavLink component. The main pain point with this approach is props spreading (typing hell).

This is especially important for md file support. Usually a MDProvider can map a markup link to just one component. It has to work for both external and internal links. Using just anchor tags here makes you loose all the advantages of client-side routing. So, I ended up with this check for my markup link component: to.toString().includes("https://") || to.toString().includes("http://") to either render an external link (anchor tag) or an internal link (NavLink component).

I believe this would be a great quality of life feature to work out of the box with react-router-dom!

timdorr commented 2 years ago

This has been requested many times before. While it works fine for external links, things get more confusing for relative URLs. For instance, if you want to download a file on your site (which isn't a route). It's impossible for us to know intent there.

You should be doing your own switching of anchor and Link/NavLink tags in your application. A heuristic-based approach would be flawed and troublesome.

ianbayne commented 5 days ago

This has been requested many times before. While it works fine for external links, things get more confusing for relative URLs. For instance, if you want to download a file on your site (which isn't a route). It's impossible for us to know intent there.

You should be doing your own switching of anchor and Link/NavLink tags in your application. A heuristic-based approach would be flawed and troublesome.

Thanks, @timdorr. I was looking for exactly this information. Is it in the docs as well? I couldn't find it.