2
2

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 1 year has passed since last update.

Next.js13のLinkコンポーネント

Last updated at Posted at 2023-03-16

この記事の目的

  • Next.jsでブログを作成したときの備忘録
  • Next.js13のLinkコンポーネントについて
  • エラーについての備忘録

概要

  • Linkコンポーネントについて
  • Next.js12と13での書き方の違い
  • 新規タブで開く際の書き方

Linkコンポーネントについて

Linkコンポーネントは画面遷移に使用するaタグのようなもの
下記のようにインポートしてから使用する

import { ImTwitter } from "react-icons/im";
import Link from "next/link"

Next.js12と13での書き方の違い

Next.js12と13でLinkコンポーネント書き方が変わったのでそれについて記載。

Next.js12の場合

import Link from 'next/link'

// Next.js12まではaタグを常にネストする必要がある
<Link href="https://twitter.com/piki_maru_ten">
     <a><ImTwitter /></a>
</Link>

Next.js13の場合

import { ImTwitter } from "react-icons/im";
import Link from 'next/link'

// Next.js13ではaタグを記載するとエラーになる
<Link href="https://twitter.com/piki_maru_ten">
     <ImTwitter />
</Link>

Next.js13ではaタグを記載すると下記のようなaタグにaタグをネストする書き方はダメ!というエラーが出ます
エラーにあるドキュメントはこちら
error.png

新規タブで開く際の書き方

aタグ必要ないのはわかったけど、新規タブで遷移させる時はどう書くのか気になったのでまとめました
Linkタグにそのままtargetとrel属性を追加すればいいだけでした

import { ImTwitter } from "react-icons/im";
import Link from 'next/link'

// Linkタグにtargetとrel属性を追加
<Link href="https://twitter.com/piki_maru_ten" target="_blank" rel="noopener noreferrer">
    <ImTwitter />
</Link>
2
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?