Unverified Commit 2451f52b authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add support for passing ref to next/link with new behavior enabled (#36537)

parent 3aa8aaae
This diff is collapsed.
...@@ -3,6 +3,7 @@ import { NextInstance } from 'test/lib/next-modes/base' ...@@ -3,6 +3,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils' import { renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import path from 'path' import path from 'path'
import webdriver from 'next-webdriver'
const appDir = path.join(__dirname, 'typescript') const appDir = path.join(__dirname, 'typescript')
...@@ -14,6 +15,7 @@ describe('New Link Behavior', () => { ...@@ -14,6 +15,7 @@ describe('New Link Behavior', () => {
files: { files: {
pages: new FileRef(path.join(appDir, 'pages')), pages: new FileRef(path.join(appDir, 'pages')),
'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')), 'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
}, },
dependencies: { dependencies: {
typescript: '*', typescript: '*',
...@@ -31,4 +33,10 @@ describe('New Link Behavior', () => { ...@@ -31,4 +33,10 @@ describe('New Link Behavior', () => {
expect($a.text()).toBe('Visit') expect($a.text()).toBe('Visit')
expect($a.attr('href')).toBe('/test') expect($a.attr('href')).toBe('/test')
}) })
it('should apply ref on link', async () => {
const browser = await webdriver(next.url, `/ref`)
const text = await browser.elementByCss('#anchor-text').text()
expect(text).toBe('AnchorText: About')
})
}) })
module.exports = {
reactStrictMode: true,
experimental: {
newNextLinkBehavior: true,
},
}
...@@ -73,6 +73,7 @@ export const ButtonLink: React.FC<ButtonLinkProps> = ({ ...@@ -73,6 +73,7 @@ export const ButtonLink: React.FC<ButtonLinkProps> = ({
shallow={shallow} shallow={shallow}
// Always passHref to the <a> component if it's defined. // Always passHref to the <a> component if it's defined.
passHref={!!href} passHref={!!href}
legacyBehavior
> >
<a>{children}</a> <a>{children}</a>
</NextLink> </NextLink>
......
import { useRef, useEffect, useState } from 'react'
import Link from 'next/link'
export default function Page() {
const ref = useRef<HTMLAnchorElement>()
const [anchorText, setAnchorText] = useState(null)
useEffect(() => {
const anchorElement = ref.current
setAnchorText(anchorElement?.textContent)
}, [])
return (
<>
{anchorText && <h1 id="anchor-text">AnchorText: {anchorText}</h1>}
<Link href="/about" ref={ref}>
About
</Link>
</>
)
}
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