2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Next.js】なぜLinkでaタグを使うのか

2
Posted at

疑問

Next.jsでなぜLink作成時にaタグが必要なのか。
以下のコードは両方とも動作するが無駄のように見える。

<Link href="/"><a>Back to home</a></Link>
<Link href="/">Back to home</Link>

答え

レンダリングされたhtmlに適切なセマンティクスが与えられるらしい。
セマンティクスが無いとSEOに悪影響を及ぼすし、アクセシビリティも悪くなる。
これについては以下のドキュメント参照。
https://nextjs.org/docs/api-reference/next/link#if-the-child-is-a-custom-component-that-wraps-an-a-tag

Linkの子コンポーネントがタグをラップするカスタムコンポーネントである場合、LinkにpassHrefを追加する必要があります。これはstyled-componentsのようなライブラリを使っている場合に必要なものです。これがないと、タグにhref属性が付かないので、サイトのSEOに悪影響が出るかもしれません。

あと、Next.js公式コードのaタグを挿入するコード部分に以下のコメントがあった。
https://github.com/vercel/next.js/blob/af3315b14d2704a58edffbf8c0c7cf4de9b44380/packages/next/client/link.tsx#L230

  // Deprecated. Warning shown by propType check. If the children provided is a string (<Link>example</Link>) we wrap it in an <a> tag
  if (typeof children === 'string') {
    children = <a>{children}</a>
  }

非推奨。propTypeチェックで表示される警告。子要素が文字列の場合(<Link>example</Link>)は、<a>タグで囲みます。

非推奨であり今後なくなる可能性があるらしい。

まとめ

書かなくてよいなら便利だと思ったけど色々問題があるようなのでこれからは書く!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?