Skip to content

Commit

Permalink
Make sure link can render without router (vercel#15604)
Browse files Browse the repository at this point in the history
This ensures rendering `next/link` doesn't fail without being nested under the router context.

Closes: vercel#15543
  • Loading branch information
ijjk authored and LauraBeatris committed Sep 1, 2020
1 parent 074c0ca commit d2e4757
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/next/client/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,15 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
const [childElm, setChildElm] = React.useState<Element>()

const router = useRouter()
const pathname = (router && router.pathname) || '/'

const { href, as } = React.useMemo(() => {
const resolvedHref = resolveHref(router.pathname, props.href)
const resolvedHref = resolveHref(pathname, props.href)
return {
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(() => {
if (p && IntersectionObserver && childElm && childElm.tagName) {
Expand Down
20 changes: 20 additions & 0 deletions test/unit/link-rendering.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* 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>"`
)
})
})

0 comments on commit d2e4757

Please sign in to comment.