๐Ÿ’ฃ Improved next/link: Simplified API with automatic <a> | Next.js 13

Boriยท2022๋…„ 12์›” 4์ผ
2

Next.js

๋ชฉ๋ก ๋ณด๊ธฐ
5/12
post-thumbnail

๐Ÿ”ช ์™œ ๊ฐ‘์ž๊ธฐ ์—๋Ÿฌ..?

  1. NavigationBar๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ํŽ˜์ด์ง€์— ์ ์šฉํ–ˆ๋‹ค.
import Link from 'next/link';

export const NavigationBar = () => {
  return (
    <nav>
      <Link href={'/'}>
        <a>Home</a>
      </Link>
      <Link href={'/about'}>
        <a>About</a>
      </Link>
    </nav>
  );
};
  1. ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค. ์™œ์ฃ ????

The next/link child can no longer be <a>. Add the legacyBehavior prop to use the legacy behavior or remove the <a> to upgrade. A codemod is available to automatically upgrade your code.
โ‡’ Next.js๊ฐ€ 13๋ฒ„์ „์„ ๋ฆด๋ฆฌ์ฆˆ ํ•˜๋ฉด์„œ Link์— aํƒœ๊ทธ๋ฅผ ์ž์‹์œผ๋กœ ์ถ”๊ฐ€ํ•  ํ•„์š”๊ฐ€ ์—†์–ด์กŒ๋‹ค!

next/link no longer requires manually adding <a> as a child.

This was added as an experimental option in 12.2 and is now the default. In Next.js 13, <Link> always renders an <a> and allows you to forward props to the underlying tag. For example:

โ‡’ Next.js 13์—์„œ <Link>๋Š” ํ•ญ์ƒ <a>ํƒœ๊ทธ๋ฅผ ๋ Œ๋”๋งํ•ฉ๋‹ˆ๋‹ค.

import Link from 'next/link'

// Next.js 12: `<a>` has to be nested otherwise it's excluded
<Link href="/about">
  <a>About</a>
</Link>

// Next.js 13: `<Link>` always renders `<a>`
<Link href="/about">
  About
</Link>

If the child is <a> tag

๋งŒ์•ฝ aํƒœ๊ทธ๋ฅผ Link์˜ ์ž์‹์œผ๋กœ ๋„ฃ๊ณ  ์‹ถ๋‹ค๋ฉด, legacyBehavior ์†์„ฑ์„ ์ถ”๊ฐ€ํ•ด์ค๋‹ˆ๋‹ค.

  • legacyBehavior - Changes behavior so that child must be <a>. Defaults to false.
    โ‡’ aํƒœ๊ทธ๊ฐ€ ์ž์‹์œผ๋กœ ๋™์ž‘ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋ณ€๊ฒฝ. ๊ธฐ๋ณธ๊ฐ’์€ false.
import Link from 'next/link'

function Legacy() {
  return (
    <Link href="/about" legacyBehavior>
      <a>About Us</a>
    </Link>
  )
}

export default Legacy

aํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์ง„ custom component ๋˜๋Š” functional component์—๋„ legacyBehavior ์†์„ฑ์„ ๋„ฃ์–ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

If the child is a custom component that wraps an <a> tag

import Link from 'next/link'
import styled from 'styled-components'

// This creates a custom component that wraps an <a> tag
const RedLink = styled.a`
  color: red;
`

function NavLink({ href, name }) {
  return (
    <Link href={href} passHref legacyBehavior>
      <RedLink>{name}</RedLink>
    </Link>
  )
}

export default NavLink

If the child is a functional component

import Link from 'next/link'

// `onClick`, `href`, and `ref` need to be passed to the DOM element
// for proper handling
const MyButton = React.forwardRef(({ onClick, href }, ref) => {
  return (
    <a href={href} onClick={onClick} ref={ref}>
      Click Me
    </a>
  )
})

function Home() {
  return (
    <Link href="/about" passHref legacyBehavior>
      <MyButton />
    </Link>
  )
}

export default Home

์ฐธ๊ณ 

0๊ฐœ์˜ ๋Œ“๊ธ€