Skip to content

Commit

Permalink
feat(remix-react): allow <Link>'s "to" prop to accept absolute urls (
Browse files Browse the repository at this point in the history
…#5092)

Signed-off-by: Logan McAnsh <logan@mcan.sh>
Co-authored-by: Matt Brophy <matt@brophy.org>
  • Loading branch information
mcansh and brophdawg11 authored Jan 25, 2023
1 parent 686e20d commit 8ba240f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
8 changes: 8 additions & 0 deletions .changeset/odd-plants-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"remix": patch
"@remix-run/react": patch
---

allow `<Link>`'s "to" prop to accept absolute urls

if absolute url, don't prefetch
18 changes: 16 additions & 2 deletions packages/remix-react/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,10 @@ function usePrefetchBehavior(
*/
let NavLink = React.forwardRef<HTMLAnchorElement, RemixNavLinkProps>(
({ to, prefetch = "none", ...props }, forwardedRef) => {
let isAbsolute =
typeof to === "string" &&
(/^[a-z+]+:\/\//i.test(to) || to.startsWith("//"));

let href = useHref(to);
let [shouldPrefetch, prefetchHandlers] = usePrefetchBehavior(
prefetch,
Expand All @@ -303,13 +307,16 @@ let NavLink = React.forwardRef<HTMLAnchorElement, RemixNavLinkProps>(
{...props}
{...prefetchHandlers}
/>
{shouldPrefetch ? <PrefetchPageLinks page={href} /> : null}
{shouldPrefetch && !isAbsolute ? (
<PrefetchPageLinks page={href} />
) : null}
</>
);
}
);
NavLink.displayName = "NavLink";
export { NavLink };

/**
* This component renders an anchor tag and is the primary way the user will
* navigate around your website.
Expand All @@ -318,11 +325,16 @@ export { NavLink };
*/
let Link = React.forwardRef<HTMLAnchorElement, RemixLinkProps>(
({ to, prefetch = "none", ...props }, forwardedRef) => {
let isAbsolute =
typeof to === "string" &&
(/^[a-z+]+:\/\//i.test(to) || to.startsWith("//"));

let href = useHref(to);
let [shouldPrefetch, prefetchHandlers] = usePrefetchBehavior(
prefetch,
props
);

return (
<>
<RouterLink
Expand All @@ -331,7 +343,9 @@ let Link = React.forwardRef<HTMLAnchorElement, RemixLinkProps>(
{...props}
{...prefetchHandlers}
/>
{shouldPrefetch ? <PrefetchPageLinks page={href} /> : null}
{shouldPrefetch && !isAbsolute ? (
<PrefetchPageLinks page={href} />
) : null}
</>
);
}
Expand Down

0 comments on commit 8ba240f

Please sign in to comment.