Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(remix-react): allow <Link>'s "to" prop to accept absolute urls #5092

Merged
merged 11 commits into from
Jan 25, 2023
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}
Comment on lines +310 to +312
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love this simplified approach 👌

</>
);
}
);
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