Unverified Commit 35f60806 authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Re-enable legacyBehavior and passHref on Link (#84500)

In https://github.com/vercel/next.js/pull/83003, `legacyBehavior` and
`passHref` were removed from `<Link>`. However, this turned out to be a
bit premature—despite most usage being covered by the newer `<Link>`
APIs, there's some use cases we don't yet have good alternatives for.

We expect to solve this with an API that uses Fragment Refs once they're
available in React. For now, we're re-enabling these flags.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 41e39426
......@@ -983,6 +983,7 @@ async fn apply_vendored_react_aliases_server(
// This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! {
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
});
}
......@@ -1012,6 +1013,7 @@ async fn rsc_aliases(
// This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! {
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
});
}
......
......@@ -860,5 +860,6 @@
"859": "An IO error occurred while attempting to create and acquire the lockfile",
"860": "Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., \"5mb\")",
"861": "Client Max Body Size must be larger than 0 bytes",
"862": "Request body exceeded %s"
"862": "Request body exceeded %s",
"863": "\\`<Link legacyBehavior>\\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \\`<a>\\` tag."
}
......@@ -238,6 +238,7 @@ export function createAppRouterApiAliases(isServerOnlyLayer: boolean) {
if (isServerOnlyLayer) {
mapping['navigation'] = 'next/dist/api/navigation.react-server'
mapping['link'] = 'next/dist/client/app-dir/link.react-server'
}
const aliasMap: Record<string, string> = {}
......
import type { ComponentProps } from 'react'
import ClientLinkComponent, { type LinkProps, useLinkStatus } from './link'
export default function LinkComponent(
props: ComponentProps<typeof ClientLinkComponent>
) {
const isLegacyBehavior = props.legacyBehavior
const childIsHostComponent =
typeof props.children === 'string' ||
typeof props.children === 'number' ||
typeof (props.children as any)?.type === 'string'
const childIsClientComponent =
(props.children as any)?.type?.$$typeof ===
Symbol.for('react.client.reference')
if (isLegacyBehavior && !childIsHostComponent && !childIsClientComponent) {
if ((props.children as any)?.type?.$$typeof === Symbol.for('react.lazy')) {
console.error(
`Using a Lazy Component as a direct child of \`<Link legacyBehavior>\` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's \`<a>\` tag.`
)
} else {
console.error(
`Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.`
)
}
}
return <ClientLinkComponent {...props} />
}
export { type LinkProps, useLinkStatus }
......@@ -22,6 +22,7 @@ import {
FetchStrategy,
type PrefetchTaskFetchStrategy,
} from '../components/segment-cache'
import { errorOnce } from '../../shared/lib/utils/error-once'
type Url = string | UrlObject
type RequiredKeys<T> = {
......@@ -110,6 +111,21 @@ type InternalLinkProps = {
*/
shallow?: boolean
/**
* Forces `Link` to pass its `href` to the child component. Useful if the child is a custom
* component that wraps an `<a>` tag, or if you're using certain styling libraries.
*
* @defaultValue `false`
*
* @example
* ```tsx
* <Link href="/dashboard" passHref legacyBehavior>
* <MyStyledAnchor>Dashboard</MyStyledAnchor>
* </Link>
* ```
*/
passHref?: boolean
/**
* Prefetch the page in the background.
* Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.
......@@ -167,6 +183,15 @@ type InternalLinkProps = {
*/
locale?: string | false
/**
* Enable legacy link behavior.
*
* @deprecated This will be removed in a future version
* @defaultValue `false`
* @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7
*/
legacyBehavior?: boolean
/**
* Optional event handler for when the mouse pointer is moved onto the `<Link>`.
*/
......@@ -198,8 +223,8 @@ export type LinkProps<RouteInferType = any> = InternalLinkProps
type LinkPropsRequired = RequiredKeys<LinkProps>
type LinkPropsOptional = OptionalKeys<Omit<InternalLinkProps, 'locale'>>
function isModifiedEvent(event: React.MouseEvent<HTMLAnchorElement>): boolean {
const eventTarget = event.currentTarget
function isModifiedEvent(event: React.MouseEvent): boolean {
const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement
const target = eventTarget.getAttribute('target')
return (
(target && target !== '_self') ||
......@@ -212,7 +237,7 @@ function isModifiedEvent(event: React.MouseEvent<HTMLAnchorElement>): boolean {
}
function linkClicked(
e: React.MouseEvent<HTMLAnchorElement>,
e: React.MouseEvent,
href: string,
as: string,
linkInstanceRef: React.RefObject<LinkInstance | null>,
......@@ -221,7 +246,14 @@ function linkClicked(
onNavigate?: OnNavigateEventHandler
): void {
if (typeof window !== 'undefined') {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
const { nodeName } = e.currentTarget
// anchors inside an svg have a lowercase nodeName
const isAnchorNodeName = nodeName.toUpperCase() === 'A'
if (
(isAnchorNodeName && isModifiedEvent(e)) ||
e.currentTarget.hasAttribute('download')
) {
// ignore click for browser’s default behavior
return
}
......@@ -294,25 +326,38 @@ export default function LinkComponent(
) {
const [linkStatus, setOptimisticLinkStatus] = useOptimistic(IDLE_LINK_STATUS)
let children: React.ReactNode
const linkInstanceRef = useRef<LinkInstance | null>(null)
const {
href: hrefProp,
as: asProp,
children,
children: childrenProp,
prefetch: prefetchProp = null,
passHref,
replace,
shallow,
scroll,
onClick,
onMouseEnter: onMouseEnterProp,
onTouchStart: onTouchStartProp,
legacyBehavior = false,
onNavigate,
ref: forwardedRef,
unstable_dynamicOnHover,
...restProps
} = props
children = childrenProp
if (
legacyBehavior &&
(typeof children === 'string' || typeof children === 'number')
) {
children = <a>{children}</a>
}
const router = React.useContext(AppRouterContext)
const prefetchEnabled = prefetchProp !== false
......@@ -369,11 +414,13 @@ export default function LinkComponent(
replace: true,
scroll: true,
shallow: true,
passHref: true,
prefetch: true,
unstable_dynamicOnHover: true,
onClick: true,
onMouseEnter: true,
onTouchStart: true,
legacyBehavior: true,
onNavigate: true,
} as const
const optionalProps: LinkPropsOptional[] = Object.keys(
......@@ -407,6 +454,8 @@ export default function LinkComponent(
key === 'replace' ||
key === 'scroll' ||
key === 'shallow' ||
key === 'passHref' ||
key === 'legacyBehavior' ||
key === 'unstable_dynamicOnHover'
) {
if (props[key] != null && valType !== 'boolean') {
......@@ -476,20 +525,64 @@ export default function LinkComponent(
}
}, [hrefProp, asProp])
// This will return the first child, if multiple are provided it will throw an error
let child: any
if (legacyBehavior) {
if ((children as any)?.$$typeof === Symbol.for('react.lazy')) {
throw new Error(
`\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.`
)
}
if (process.env.NODE_ENV === 'development') {
if (onClick) {
console.warn(
`"onClick" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onClick be set on the child of next/link`
)
}
if (onMouseEnterProp) {
console.warn(
`"onMouseEnter" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onMouseEnter be set on the child of next/link`
)
}
try {
child = React.Children.only(children)
} catch (err) {
if (!children) {
throw new Error(
`No children were passed to <Link> with \`href\` of \`${hrefProp}\` but one child is required https://nextjs.org/docs/messages/link-no-children`
)
}
throw new Error(
`Multiple children were passed to <Link> with \`href\` of \`${hrefProp}\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` +
(typeof window !== 'undefined'
? " \nOpen your browser's console to view the Component stack trace."
: '')
)
}
} else {
child = React.Children.only(children)
}
} else {
if (process.env.NODE_ENV === 'development') {
if ((children as any)?.type === 'a') {
throw new Error(
'Invalid <Link> with <a> child. Please remove <a>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'
'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'
)
}
}
}
const childRef: any = legacyBehavior
? child && typeof child === 'object' && child.ref
: forwardedRef
// Use a callback ref to attach an IntersectionObserver to the anchor tag on
// mount. In the future we will also use this to keep track of all the
// currently mounted <Link> instances, e.g. so we can re-prefetch them after
// a revalidation or refresh.
const observeLinkVisibilityOnMount = React.useCallback(
(element: HTMLAnchorElement) => {
(element: HTMLAnchorElement | SVGAElement) => {
if (router !== null) {
linkInstanceRef.current = mountLinkInstance(
element,
......@@ -512,76 +605,135 @@ export default function LinkComponent(
[prefetchEnabled, href, router, fetchStrategy, setOptimisticLinkStatus]
)
const mergedRef = useMergedRef(observeLinkVisibilityOnMount, forwardedRef)
const mergedRef = useMergedRef(observeLinkVisibilityOnMount, childRef)
const anchorProps: React.DetailedHTMLProps<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
> = {
const childProps: {
onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>
onMouseEnter: React.MouseEventHandler<HTMLAnchorElement>
onClick: React.MouseEventHandler<HTMLAnchorElement>
href?: string
ref?: any
} = {
ref: mergedRef,
onClick(e) {
if (typeof onClick === 'function') {
if (process.env.NODE_ENV !== 'production') {
if (!e) {
throw new Error(
`Component rendered inside next/link has to pass click event to "onClick" prop.`
)
}
}
if (!legacyBehavior && typeof onClick === 'function') {
onClick(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onClick === 'function'
) {
child.props.onClick(e)
}
if (!router) {
return
}
if (e.defaultPrevented) {
return
}
linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate)
},
onMouseEnter(e) {
if (typeof onMouseEnterProp === 'function') {
if (!legacyBehavior && typeof onMouseEnterProp === 'function') {
onMouseEnterProp(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onMouseEnter === 'function'
) {
child.props.onMouseEnter(e)
}
if (!router) {
return
}
if (!prefetchEnabled || process.env.NODE_ENV === 'development') {
return
}
const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true
onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)
onNavigationIntent(
e.currentTarget as HTMLAnchorElement | SVGAElement,
upgradeToDynamicPrefetch
)
},
onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START
? undefined
: function onTouchStart(e) {
if (typeof onTouchStartProp === 'function') {
if (!legacyBehavior && typeof onTouchStartProp === 'function') {
onTouchStartProp(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onTouchStart === 'function'
) {
child.props.onTouchStart(e)
}
if (!router) {
return
}
if (!prefetchEnabled) {
return
}
const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true
onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)
onNavigationIntent(
e.currentTarget as HTMLAnchorElement | SVGAElement,
upgradeToDynamicPrefetch
)
},
}
// If the url is absolute, we can bypass the logic to prepend the basePath.
if (isAbsoluteUrl(as)) {
anchorProps.href = as
childProps.href = as
} else if (
!legacyBehavior ||
passHref ||
(child.type === 'a' && !('href' in child.props))
) {
childProps.href = addBasePath(as)
}
let link: React.ReactNode
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
errorOnce(
'`legacyBehavior` is deprecated and will be removed in a future ' +
'release. A codemod is available to upgrade your components:\n\n' +
'npx @next/codemod@latest new-link .\n\n' +
'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'
)
}
link = React.cloneElement(child, childProps)
} else {
anchorProps.href = addBasePath(as)
link = (
<a {...restProps} {...childProps}>
{children}
</a>
)
}
return (
<LinkStatusContext.Provider value={linkStatus}>
<a {...restProps} {...anchorProps}>
{children}
</a>
{link}
</LinkStatusContext.Provider>
)
}
......
......@@ -17,7 +17,9 @@ import { startTransition } from 'react'
import { PrefetchKind } from './router-reducer/router-reducer-types'
import { InvariantError } from '../../shared/lib/invariant-error'
type Element = HTMLAnchorElement | HTMLFormElement
type LinkElement = HTMLAnchorElement | SVGAElement
type Element = LinkElement | HTMLFormElement
// Properties that are shared between Link and Form instances. We use the same
// shape for both to prevent a polymorphic de-opt in the VM.
......@@ -145,7 +147,7 @@ function coercePrefetchableUrl(href: string): URL | null {
}
export function mountLinkInstance(
element: HTMLAnchorElement,
element: LinkElement,
href: string,
router: AppRouterInstance,
fetchStrategy: PrefetchTaskFetchStrategy,
......@@ -255,7 +257,7 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) {
}
export function onNavigationIntent(
element: HTMLAnchorElement,
element: HTMLAnchorElement | SVGAElement,
unstable_upgradeToDynamicPrefetch: boolean
) {
const instance = prefetchable.get(element)
......
......@@ -18,6 +18,7 @@ import { useIntersection } from './use-intersection'
import { getDomainLocale } from './get-domain-locale'
import { addBasePath } from './add-base-path'
import { useMergedRef } from './use-merged-ref'
import { errorOnce } from '../shared/lib/utils/error-once'
type Url = string | UrlObject
type RequiredKeys<T> = {
......@@ -60,6 +61,12 @@ type InternalLinkProps = {
* @defaultValue `false`
*/
shallow?: boolean
/**
* Forces `Link` to send the `href` property to its child.
*
* @defaultValue `false`
*/
passHref?: boolean
/**
* Prefetch the page in the background.
* Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.
......@@ -82,6 +89,14 @@ type InternalLinkProps = {
* Note: This is only available in the Pages Router.
*/
locale?: string | false
/**
* Enable legacy link behavior.
*
* @deprecated This will be removed in a future version
* @defaultValue `false`
* @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7
*/
legacyBehavior?: boolean
/**
* Optional event handler for when the mouse pointer is moved onto Link
*/
......@@ -173,7 +188,7 @@ function prefetch(
}
function isModifiedEvent(event: React.MouseEvent): boolean {
const eventTarget = event.currentTarget as HTMLAnchorElement
const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement
const target = eventTarget.getAttribute('target')
return (
(target && target !== '_self') ||
......@@ -196,7 +211,15 @@ function linkClicked(
locale?: string | false,
onNavigate?: OnNavigateEventHandler
): void {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
const { nodeName } = e.currentTarget
// anchors inside an svg have a lowercase nodeName
const isAnchorNodeName = nodeName.toUpperCase() === 'A'
if (
(isAnchorNodeName && isModifiedEvent(e)) ||
e.currentTarget.hasAttribute('download')
) {
// ignore click for browser’s default behavior
return
}
......@@ -271,11 +294,14 @@ function formatStringOrUrl(urlObjOrString: UrlObject | string): string {
*/
const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
function LinkComponent(props, forwardedRef) {
let children: React.ReactNode
const {
href: hrefProp,
as: asProp,
children,
children: childrenProp,
prefetch: prefetchProp = null,
passHref,
replace,
shallow,
scroll,
......@@ -284,9 +310,19 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
onNavigate,
onMouseEnter: onMouseEnterProp,
onTouchStart: onTouchStartProp,
legacyBehavior = false,
...restProps
} = props
children = childrenProp
if (
legacyBehavior &&
(typeof children === 'string' || typeof children === 'number')
) {
children = <a>{children}</a>
}
const router = React.useContext(RouterContext)
const prefetchEnabled = prefetchProp !== false
......@@ -338,11 +374,13 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
replace: true,
scroll: true,
shallow: true,
passHref: true,
prefetch: true,
locale: true,
onClick: true,
onMouseEnter: true,
onTouchStart: true,
legacyBehavior: true,
onNavigate: true,
} as const
const optionalProps: LinkPropsOptional[] = Object.keys(
......@@ -380,7 +418,13 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
actual: valType,
})
}
} else if (key === 'replace' || key === 'scroll' || key === 'shallow') {
} else if (
key === 'replace' ||
key === 'scroll' ||
key === 'shallow' ||
key === 'passHref' ||
key === 'legacyBehavior'
) {
if (props[key] != null && valType !== 'boolean') {
throw createPropError({
key,
......@@ -428,21 +472,57 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
const previousHref = React.useRef<string>(href)
const previousAs = React.useRef<string>(as)
// This will return the first child, if multiple are provided it will throw an error
let child: any
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
if (onClick) {
console.warn(
`"onClick" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onClick be set on the child of next/link`
)
}
if (onMouseEnterProp) {
console.warn(
`"onMouseEnter" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onMouseEnter be set on the child of next/link`
)
}
try {
child = React.Children.only(children)
} catch (err) {
if (!children) {
throw new Error(
`No children were passed to <Link> with \`href\` of \`${hrefProp}\` but one child is required https://nextjs.org/docs/messages/link-no-children`
)
}
throw new Error(
`Multiple children were passed to <Link> with \`href\` of \`${hrefProp}\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` +
(typeof window !== 'undefined'
? " \nOpen your browser's console to view the Component stack trace."
: '')
)
}
} else {
child = React.Children.only(children)
}
} else {
if (process.env.NODE_ENV === 'development') {
if ((children as any)?.type === 'a') {
throw new Error(
'Invalid <Link> with <a> child. Please remove <a>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'
'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'
)
}
}
}
const childRef: any = legacyBehavior
? child && typeof child === 'object' && child.ref
: forwardedRef
const [setIntersectionRef, isVisible, resetVisible] =
useIntersection<HTMLAnchorElement>({
const [setIntersectionRef, isVisible, resetVisible] = useIntersection({
rootMargin: '200px',
})
const setIntersectionWithResetRef = React.useCallback(
(el: HTMLAnchorElement | null) => {
(el: Element | null) => {
// Before the link getting observed, check if visible state need to be reset
if (previousAs.current !== as || previousHref.current !== href) {
resetVisible()
......@@ -455,7 +535,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
[as, href, resetVisible, setIntersectionRef]
)
const setRef = useMergedRef(setIntersectionWithResetRef, forwardedRef)
const setRef = useMergedRef(setIntersectionWithResetRef, childRef)
// Prefetch the URL if we haven't already and it's visible.
React.useEffect(() => {
......@@ -477,16 +557,35 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
prefetch(router, href, as, { locale })
}, [as, href, isVisible, locale, prefetchEnabled, router?.locale, router])
const anchorProps: React.DetailedHTMLProps<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
> = {
const childProps: {
onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>
onMouseEnter: React.MouseEventHandler<HTMLAnchorElement>
onClick: React.MouseEventHandler<HTMLAnchorElement>
href?: string
ref?: any
} = {
ref: setRef,
onClick(e) {
if (typeof onClick === 'function') {
if (process.env.NODE_ENV !== 'production') {
if (!e) {
throw new Error(
`Component rendered inside next/link has to pass click event to "onClick" prop.`
)
}
}
if (!legacyBehavior && typeof onClick === 'function') {
onClick(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onClick === 'function'
) {
child.props.onClick(e)
}
if (!router) {
return
}
......@@ -508,10 +607,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
)
},
onMouseEnter(e) {
if (typeof onMouseEnterProp === 'function') {
if (!legacyBehavior && typeof onMouseEnterProp === 'function') {
onMouseEnterProp(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onMouseEnter === 'function'
) {
child.props.onMouseEnter(e)
}
if (!router) {
return
}
......@@ -526,10 +633,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START
? undefined
: function onTouchStart(e) {
if (typeof onTouchStartProp === 'function') {
if (!legacyBehavior && typeof onTouchStartProp === 'function') {
onTouchStartProp(e)
}
if (
legacyBehavior &&
child.props &&
typeof child.props.onTouchStart === 'function'
) {
child.props.onTouchStart(e)
}
if (!router) {
return
}
......@@ -545,8 +660,12 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
// If the url is absolute, we can bypass the logic to prepend the domain and locale.
if (isAbsoluteUrl(as)) {
anchorProps.href = as
} else {
childProps.href = as
} else if (
!legacyBehavior ||
passHref ||
(child.type === 'a' && !('href' in child.props))
) {
const curLocale = typeof locale !== 'undefined' ? locale : router?.locale
// we only render domain locales if we are currently on a domain locale
......@@ -555,13 +674,25 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
router?.isLocaleDomain &&
getDomainLocale(as, curLocale, router?.locales, router?.domainLocales)
anchorProps.href =
childProps.href =
localeDomain ||
addBasePath(addLocale(as, curLocale, router?.defaultLocale))
}
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
errorOnce(
'`legacyBehavior` is deprecated and will be removed in a future ' +
'release. A codemod is available to upgrade your components:\n\n' +
'npx @next/codemod@latest new-link .\n\n' +
'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'
)
}
return React.cloneElement(child, childProps)
}
return (
<a {...restProps} {...anchorProps}>
<a {...restProps} {...childProps}>
{children}
</a>
)
......
import { nextTestSetup } from 'e2e-utils'
describe('Link with legacyBehavior', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
describe('if the child is an <a> tag', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('#about-page').text()
expect(title).toBe('About Page')
})
})
it('works if the child is a number', async () => {
const browser = await next.browser('/child-is-a-number')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('works if the child is a string', async () => {
const browser = await next.browser('/child-is-a-string')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('errors when calling onClick without the event', async () => {
const browser = await next.browser('/invalid-onclick')
expect(await browser.elementByCss('#errors').text()).toBe('0')
await browser.elementByCss('#custom-button').click()
expect(await browser.elementByCss('#errors').text()).toBe('1')
})
it('should show a deprecation warning', async () => {
const browser = await next.browser('/')
const logs = await browser.log()
const errors = logs.filter(
(log) =>
log.source === 'error' &&
log.message.includes(
'`legacyBehavior` is deprecated and will be removed in a future release.'
)
)
console.log(errors)
expect(errors.length).toBe(isNextDev ? 1 : 0)
})
describe('passHref', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/passHref')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/passHref')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
})
})
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="about-page">About Page</h1>
<Link href="/" legacyBehavior>
<a>Home</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
{1000}
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Home Page</h1>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
import Link from 'next/link'
import { useState } from 'react'
export default function Page(props: any) {
const [errorCount, setErrorCount] = useState(0)
function Button(props) {
return (
<a
id="custom-button"
href={props.href}
onClick={(e) => {
e.preventDefault()
try {
props.onClick()
} catch (err) {
setErrorCount(errorCount + 1)
console.error(err)
}
}}
>
{props.href}
</a>
)
}
return (
<>
<p id="errors">{errorCount}</p>
<Link href="/nav" passHref legacyBehavior>
<Button />
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<CustomComponent>About</CustomComponent>
</Link>
</>
)
}
function CustomComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="about-page">About Page</h1>
<Link href="/" legacyBehavior>
<a>Home</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
{1000}
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export default function Page(props: any) {
const [errorCount, setErrorCount] = useState(0)
function Button(props) {
return (
<a
id="custom-button"
href={props.href}
onClick={(e) => {
e.preventDefault()
try {
props.onClick()
} catch (err) {
setErrorCount(errorCount + 1)
console.error(err)
}
}}
>
{props.href}
</a>
)
}
return (
<>
<p id="errors">{errorCount}</p>
<Link href="/nav" passHref legacyBehavior>
<Button />
</Link>
</>
)
}
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default async function Root({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<Suspense>
<Connection>
<body>{children}</body>
</Connection>
</Suspense>
</html>
)
}
async function Connection({ children }: { children: ReactNode }) {
await connection()
return children
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Home Page</h1>
<Link href="/about" legacyBehavior>
<a>About</a>
</Link>
</>
)
}
'use client'
export default function CustomComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import CustomComponent from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<CustomComponent>About</CustomComponent>
</Link>
</>
)
}
'use client'
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ChildComponent>About</ChildComponent>
</Link>
</>
)
}
function ChildComponent(props: any) {
return <a {...props} />
}
'use client'
import Link from 'next/link'
import { lazy } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
{/* @ts-ignore */}
{lazyJSX}
</Link>
</>
)
}
// @ts-ignore
const lazyJSX = lazy(() => Promise.resolve({ default: <a>About</a> }))
'use client'
import Link from 'next/link'
export default function Page() {
return <Link href="/about" legacyBehavior></Link>
}
'use client'
import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" legacyBehavior>
<span>a</span>
<span>b</span>
</Link>
)
}
import { ReactNode } from 'react'
import { ClientLink } from '../client-link'
export default function Page() {
return (
<>
<ClientLink href="/about">
<RSC>About</RSC>
</ClientLink>
</>
)
}
async function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
'use client'
import Link from 'next/link'
import { ComponentProps } from 'react'
export function ClientLink(props: ComponentProps<typeof Link>) {
return <Link legacyBehavior passHref {...props} />
}
'use client'
import { ReactNode } from 'react'
export default function ClientA({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { ClientLink } from '../client-link'
import ClientA from './_client'
export default function Page() {
return (
<>
<ClientLink href="/about">
<ClientA>
<RSC />
</ClientA>
</ClientLink>
</>
)
}
async function RSC() {
return <span>About</span>
}
'use client'
import { ReactNode } from 'react'
export default function ClientA({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { ClientLink } from '../client-link'
import ClientA from './_client'
export default function Page() {
return (
<>
<ClientLink href="/about">
<ClientA>About</ClientA>
</ClientLink>
</>
)
}
import { ReactNode } from 'react'
import { ClientLink } from '../client-link'
export default function Page() {
return (
<>
<ClientLink href="/about">
<RSC>About</RSC>
</ClientLink>
</>
)
}
function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
<RSC>About</RSC>
</Link>
</>
)
}
async function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
'use client'
export function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { ClientComponent } from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ClientComponent>
<RSC />
</ClientComponent>
</Link>
</>
)
}
function RSC() {
return <span>About</span>
}
'use client'
export function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { ClientComponent } from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ClientComponent>About</ClientComponent>
</Link>
</>
)
}
'use client'
export default function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { lazy } from 'react'
const LazyComponent = lazy(() => import('./_client'))
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<LazyComponent>About</LazyComponent>
</Link>
</>
)
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
<RSC>About</RSC>
</Link>
</>
)
}
function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Link with legacyBehavior', () => {
if (process.env.__NEXT_EXPERIMENTAL_DEBUG_CHANNEL) {
it('should skip debug mode test', () => {})
return
}
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return it('should skip', () => {})
}
describe('if the child is an <a> tag', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('#about-page').text()
expect(title).toBe('About Page')
})
})
it('works if the child is a number', async () => {
const browser = await next.browser('/child-is-a-number')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('works if the child is a string', async () => {
const browser = await next.browser('/child-is-a-string')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('errors when calling onClick without the event', async () => {
const browser = await next.browser('/invalid-onclick')
expect(await browser.elementByCss('#errors').text()).toBe('0')
await browser.elementByCss('#custom-button').click()
expect(await browser.elementByCss('#errors').text()).toBe('1')
})
it('should show a deprecation warning', async () => {
const browser = await next.browser('/')
await retry(async () => {
const logs = await browser.log()
const errors = logs.filter((log) => log.source === 'error')
if (isNextDev) {
expect(errors).toEqual([
{
message:
'`legacyBehavior` is deprecated and will be removed in a future release. A codemod is available to upgrade your components:\n\n' +
'npx @next/codemod@latest new-link .\n\n' +
'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components',
source: 'error',
},
])
} else {
expect(errors).toEqual([])
}
})
})
describe('passHref', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/passHref')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/passHref')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
cacheComponents: true,
},
}
module.exports = nextConfig
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { assertNoRedbox } from 'next-test-utils'
describe('Validations for <Link legacyBehavior>', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (isNextDeploy) {
return it('should skip deploy', () => {})
}
let previousOutputIndex
beforeEach(() => {
previousOutputIndex = next.cliOutput.length
})
function newConsoleOutput() {
return next.cliOutput.slice(previousOutputIndex)
}
describe('When rendering from a Server Component', () => {
describe('Rendering <Link> directly', () => {
it('warns if the child is a synchronous server component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-link/synchronous'
)
if (isNextDev) {
await expect(browser).toDisplayCollapsedRedbox(`
[
{
"description": "Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/validations/rsc-that-renders-link/synchronous/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/synchronous/page.tsx (7:7)",
],
},
{
"description": "\`legacyBehavior\` is deprecated and will be removed in a future release. A codemod is available to upgrade your components:
npx @next/codemod@latest new-link .
Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components",
"environmentLabel": null,
"label": "Console Error",
"source": "app/validations/rsc-that-renders-link/synchronous/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/synchronous/page.tsx (7:7)",
],
},
]
`)
} else {
expect(newConsoleOutput()).toMatchInlineSnapshot(`
"Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.
"
`)
}
})
it('warns and throws an error if the child is an asynchronous server component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-link/asynchronous'
)
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
[
{
"description": "Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/validations/rsc-that-renders-link/asynchronous/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/asynchronous/page.tsx (7:7)",
],
},
{
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-link/asynchronous/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/asynchronous/page.tsx (7:7)",
],
},
]
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(`
"Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.
⨯ Error: \`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag."
`)
}
})
if (!process.env.__NEXT_EXPERIMENTAL_DEBUG_CHANNEL) {
it('does not warn or throw if you pass a client component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-link/client'
)
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
it('does not warn or throw if you pass a server component into a client component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-link/client-with-rsc-child'
)
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
}
it('warns if the child is a lazy component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-link/lazy'
)
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
[
{
"description": "Using a Lazy Component as a direct child of \`<Link legacyBehavior>\` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/validations/rsc-that-renders-link/lazy/page.tsx (9:7) @ Page
> 9 | <Link href="/about" legacyBehavior passHref>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/lazy/page.tsx (9:7)",
],
},
{
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-link/lazy/page.tsx (9:7) @ Page
> 9 | <Link href="/about" legacyBehavior passHref>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/lazy/page.tsx (9:7)",
],
},
]
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(`
"Using a Lazy Component as a direct child of \`<Link legacyBehavior>\` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's \`<a>\` tag.
⨯ Error: \`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag."
`)
}
})
})
describe('Rendering a Client Component that renders <Link>', () => {
it('does not warn if the child is a synchronous server component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-client/synchronous'
)
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
it('throws an error if the child is an asynchronous server component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-client/asynchronous'
)
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
{
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-client/client-link.tsx (7:10) @ ClientLink
> 7 | return <Link legacyBehavior passHref {...props} />
| ^",
"stack": [
"ClientLink app/validations/rsc-that-renders-client/client-link.tsx (7:10)",
"Page app/validations/rsc-that-renders-client/asynchronous/page.tsx (7:7)",
],
}
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(
`" ⨯ Error: \`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag."`
)
}
})
if (!process.env.__NEXT_EXPERIMENTAL_DEBUG_CHANNEL) {
it('does not warn or throw if you pass a client component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-client/client'
)
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
it('does not warn or throw if you pass a server component into a client component', async () => {
const browser = await next.browser(
'/validations/rsc-that-renders-client/client-with-rsc-child'
)
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
}
})
})
describe('When rendering from a Client Component', () => {
it('errors if there are no children', async () => {
const browser = await next.browser('/validations/client/missing-child')
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
{
"description": "No children were passed to <Link> with \`href\` of \`/about\` but one child is required https://nextjs.org/docs/messages/link-no-children",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/client/missing-child/page.tsx (6:10) @ Page
> 6 | return <Link href="/about" legacyBehavior></Link>
| ^",
"stack": [
"Page app/validations/client/missing-child/page.tsx (6:10)",
],
}
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(
`" ⨯ Error: React.Children.only expected to receive a single React element child."`
)
}
})
it('errors if there are multiple children', async () => {
const browser = await next.browser(
'/validations/client/multiple-children'
)
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
{
"description": "Multiple children were passed to <Link> with \`href\` of \`/about\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children
Open your browser's console to view the Component stack trace.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/client/multiple-children/page.tsx (7:5) @ Page
> 7 | <Link href="/about" legacyBehavior>
| ^",
"stack": [
"Page app/validations/client/multiple-children/page.tsx (7:5)",
],
}
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(
`" ⨯ Error: React.Children.only expected to receive a single React element child."`
)
}
})
it('does not warn or throw if you pass a child component', async () => {
const browser = await next.browser('/validations/client/child-component')
if (isNextDev) {
await assertNoRedbox(browser)
} else {
expect(newConsoleOutput()).toEqual('')
}
})
it('warns and throws an error if the child is lazy JSX', async () => {
const browser = await next.browser('/validations/client/lazy-jsx')
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
{
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/client/lazy-jsx/page.tsx (9:7) @ Page
> 9 | <Link href="/about" legacyBehavior passHref>
| ^",
"stack": [
"Page app/validations/client/lazy-jsx/page.tsx (9:7)",
],
}
`)
} else {
const output = getContentBetween({
input: newConsoleOutput(),
endContent: ' at',
})
expect(output).toMatchInlineSnapshot(
`" ⨯ Error: \`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag."`
)
}
})
})
})
function getContentBetween({
input,
startContent,
endContent,
}: {
input: string
startContent?: string
endContent?: string
}): string {
const lines = input.split('\n')
const startIdx = startContent
? lines.findIndex((line) => line.includes(startContent))
: -1
const endIdx = endContent
? lines.findIndex((line) => line.includes(endContent))
: -1
if (startContent && startIdx < 0) return ''
if (endContent && endIdx >= 0 && endIdx <= startIdx) return ''
const sliceStart = startIdx >= 0 ? startIdx + 1 : 0
const sliceEnd = endIdx > sliceStart ? endIdx : undefined
return lines.slice(sliceStart, sliceEnd).join('\n')
}
......@@ -27,11 +27,11 @@ describe('New Link Behavior with <a> child', () => {
if (isNextDev) {
expect(next.cliOutput).toContain(
'Error: Invalid <Link> with <a> child. Please remove <a>'
'Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>'
)
await expect(browser).toDisplayRedbox(`
{
"description": "Invalid <Link> with <a> child. Please remove <a>.
"description": "Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.
Learn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor",
"environmentLabel": null,
"label": "Runtime Error",
......
......@@ -3,15 +3,9 @@ import { textValue, TestLink } from './lib/shared-module'
export function middleware(request) {
if (request.nextUrl.pathname === '/middleware') {
let testLink
try {
testLink = TestLink.$$typeof.toString()
} catch (e) {
testLink = e.message
}
return Response.json({
clientReference: testLink,
textValue,
linkType: typeof TestLink,
})
}
......
......@@ -10,7 +10,7 @@ describe('rsc layers transform', () => {
expect(json).toEqual({
textValue: 'text-value',
clientReference: 'Symbol(react.client.reference)',
linkType: 'function',
})
})
......
import * as React from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Navigation worked!</h1>
<Link href="/">Go back</Link>
</>
)
}
/** @type {import('next').NextConfig} */
export default {}
'use client'
import Link from 'next/link'
import {
useCallback,
useState,
type ComponentPropsWithRef,
type ReactNode,
type Ref,
type RefCallback,
} from 'react'
export default function Page() {
return (
<>
<h1>Home</h1>
<ToggleVisibility>
<Link href="/link-target" legacyBehavior>
<AnchorThatDoesRefMerging id="test-link">
Go to /link-target
</AnchorThatDoesRefMerging>
</Link>
</ToggleVisibility>
</>
)
}
function ToggleVisibility({ children }: { children: ReactNode }) {
const [isVisible, setIsVisible] = useState(true)
return (
<>
<div>
<button type="button" onClick={() => setIsVisible((prev) => !prev)}>
{isVisible ? 'Hide content' : 'Show content'}
</button>
</div>
{isVisible ? children : null}
</>
)
}
function AnchorThatDoesRefMerging({
ref,
children,
...anchorProps
}: ComponentPropsWithRef<'a'>) {
const customRef: RefCallback<HTMLAnchorElement> = useCallback((el) => {
if (el) {
console.log('hello friends i am here')
} else {
console.log('goodbye friends i am gone')
}
}, [])
const finalRef = useBuggyRefMerge(customRef, ref ?? null)
return (
<a ref={finalRef} {...anchorProps}>
{children}
</a>
)
}
/** A ref-merging function that doesn't account for cleanup refs (added in React 19)
* https://react.dev/blog/2024/12/05/react-19#cleanup-functions-for-refs
*/
function useBuggyRefMerge<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): RefCallback<TElement> {
return useCallback(
(current: TElement | null) => {
for (const ref of [refA, refB]) {
if (!ref) {
continue
}
if (typeof ref === 'object') {
ref.current = current
} else {
// BUG!!!
// This would work in 18, but in 19 it can return a cleanup which will get swallowed here
ref(current)
}
}
},
[refA, refB]
)
}
import { nextTestSetup } from 'e2e-utils'
// NOTE: this test is checking for a bug in prefetching code,
// so we only enable it in production
describe('Link with legacyBehavior - handles buggy userspace ref merging', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('does not crash when Link unmounts', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('h1').text()).toEqual('Home')
expect(await browser.hasElementByCssSelector('#test-link')).toBe(true)
// hide the link, unmounting it
await browser.elementByCss('button').click()
expect(await browser.hasElementByCssSelector('#test-link')).toBe(false)
// shouldn't cause a crash
expect(await browser.elementByCss('h1').text()).toEqual('Home')
expect(await browser.elementByCss('body').text()).not.toContain(
'Application error: a client-side exception has occurred'
)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment