Unverified Commit 86ba29f6 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Make sure link can render without router (#15604)

This ensures rendering `next/link` doesn't fail without being nested under the router context.

Closes: https://github.com/vercel/next.js/issues/15543
parent 39607839
...@@ -166,14 +166,15 @@ function Link(props: React.PropsWithChildren<LinkProps>) { ...@@ -166,14 +166,15 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
const [childElm, setChildElm] = React.useState<Element>() const [childElm, setChildElm] = React.useState<Element>()
const router = useRouter() const router = useRouter()
const pathname = (router && router.pathname) || '/'
const { href, as } = React.useMemo(() => { const { href, as } = React.useMemo(() => {
const resolvedHref = resolveHref(router.pathname, props.href) const resolvedHref = resolveHref(pathname, props.href)
return { return {
href: resolvedHref, href: resolvedHref,
as: props.as ? resolveHref(router.pathname, props.as) : resolvedHref, as: props.as ? resolveHref(pathname, props.as) : resolvedHref,
} }
}, [router.pathname, props.href, props.as]) }, [pathname, props.href, props.as])
React.useEffect(() => { React.useEffect(() => {
if (p && IntersectionObserver && childElm && childElm.tagName) { if (p && IntersectionObserver && childElm && childElm.tagName) {
......
/* eslint-env jest */
import React from 'react'
import ReactDOM from 'react-dom/server'
import Link from 'next/link'
describe('Link rendering', () => {
it('should render Link on its own', async () => {
const element = React.createElement(
Link,
{
href: '/my-path',
},
React.createElement('a', {}, 'to another page')
)
const html = ReactDOM.renderToString(element)
expect(html).toMatchInlineSnapshot(
`"<a href=\\"/my-path\\" data-reactroot=\\"\\">to another page</a>"`
)
})
})
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