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

Require component rendered as child of Link to pass event to onClick handler #27723

Merged
merged 3 commits into from Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/next/client/link.tsx
Expand Up @@ -284,6 +284,13 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
} = {
ref: setRef,
onClick: (e: React.MouseEvent) => {
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 (child.props && typeof child.props.onClick === 'function') {
child.props.onClick(e)
}
Expand Down
@@ -0,0 +1,35 @@
import Link from 'next/link'
import { useState } from 'react'

export default function Page(props) {
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>
<Button />
</Link>
</>
)
}
7 changes: 7 additions & 0 deletions test/integration/client-navigation/test/index.test.js
Expand Up @@ -87,6 +87,13 @@ describe('Client Navigation', () => {
expect(text).toMatch(/this is the about page/i)
})

it('should error when calling onClick without event', async () => {
const browser = await webdriver(context.appPort, '/link-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 navigate via the client side', async () => {
const browser = await webdriver(context.appPort, '/nav')

Expand Down