From 18a05304db77e3bad8311b4745b75180b512eb87 Mon Sep 17 00:00:00 2001 From: GUEZOU Damien Date: Fri, 31 Mar 2023 09:16:16 +0200 Subject: [PATCH] fix(Link): Link parsing from an UrlObject href In next js when a href is set with a UrlObject. It threw an error --- src/link.tsx | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/link.tsx b/src/link.tsx index 4a36a95d6..6b24dc6dc 100644 --- a/src/link.tsx +++ b/src/link.tsx @@ -1,4 +1,5 @@ import React, { type ReactNode, type DetailedHTMLProps, type AnchorHTMLAttributes } from "react"; +import { UrlObject, format } from "url"; type HTMLAnchorProps = DetailedHTMLProps< AnchorHTMLAttributes, @@ -18,12 +19,26 @@ let Link: ( props: RegisteredLinkProps & { children: ReactNode } ) => ReturnType = props => ; +/** + * Returns a url string from an Link href. If the link href is an UrlObject, it is converted to a string + * + * Return undefined if the href params is undefined + */ +function getUrlStringFromLinkHref(href: string | UrlObject | undefined): string | undefined { + if (href === undefined || typeof href === "string") { + return href; + } + + // format is deprecated but didn't find a real alternative yet + return format(href); +} + export function setLink(params: { Link: typeof Link }): void { Link = props => { { - const { to, href, ...rest } = props as { to?: string; href?: string }; + const { to, href, ...rest } = props as { to?: string; href?: string | UrlObject }; - const target = to ?? href; + const target = to ?? getUrlStringFromLinkHref(href); mailto: { if (target === undefined || !target.startsWith("mailto:")) {