15
5

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.js】Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.が表示されたときの対処法

Posted at

Next.jsで'next/link'の機能を使いページ間のLinkを設定しようとした時
このようなエラーがでてきました。

Unhandled Runtime Error
Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.
Learn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor

設定したソースはこちらです。

nav.js
import Link from "next/link";

export default function Nav() {
  return (
    <nav>
      <ul>
        <li>
          <Link href="/">
            <a>HOME</a>
          </Link>
        </li>
        <li>
          <Link href="/about">
            <a>ABOUT</a>
          </Link>
        </li>
        <li>
          <Link href="/blog">
            <a>BLOG</a>
          </Link>
        </li>
      </ul>
    </nav>
  );
}

エラー内容を読んでみると、aタグを削除するかにlegacyBehaviorの値をつけたらよいようです。

特にaタグが必要ないなら削除します。

nav.js
import Link from "next/link";

export default function Nav() {
  return (
    <nav>
      <ul>
        <li>
          <Link href="/">
            HOME
          </Link>
        </li>
        <li>
          <Link href="/about">
            ABOUT
          </Link>
        </li>
        <li>
          <Link href="/blog">
            BLOG
          </Link>
        </li>
      </ul>
    </nav>
  );
}

classをつけたりするため必要な場合はLinklegacyBehaviorを設定します。

nav.js
import Link from "next/link";

export default function Nav() {
  return (
    <nav>
      <ul>
        <li>
          <Link href="/" legacyBehavior>
            <a className="home">HOME</a>
          </Link>
        </li>
        <li>
          <Link href="/about" legacyBehavior>
            <a className="about">ABOUT</a>
          </Link>
        </li>
        <li>
          <Link href="/blog" legacyBehavior>
            <a className="blog">BLOG</a>
          </Link>
        </li>
      </ul>
    </nav>
  );
}

これでエラーが無くなりました。

15
5
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
15
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?