NEXT.js Link error

김병민·2022년 9월 18일
1

그냥 내 err

목록 보기
13/17
post-thumbnail

Next Link

클라이언트에서 경로간의 이동은 Link 컴포넌트를 사용하여 가능하다.

사용법

import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About Us</a>
        </Link>
      </li>
      <li>
        <Link href="/blog/hello-world">
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home

에러

Unhandled Runtime Error
Error: Multiple children were passed to <Link> with href of / but only one child is supported https://nextjs.org/docs/messages/link-multiple-children
Open your browser's console to view the Component stack trace.

원인

원인( 1 )

import Link from 'next/link'

export default function Home() {
  return (
    <Link href="/about">
      <a>To About</a>
      <a>Second To About</a>
    </Link>
  )
}

위와 같이 하나의 Link컴포넌트 안에 두 개 이상의 컴포넌트 혹은 태그를 넣을 시 발생

해결 ( 1 )

import Link from 'next/link'

export default function Home() {
  return (
    <>
      <Link href="/about">
        <a>To About</a>
      </Link>
      <Link href="/about">
        <a>Second To About</a>
      </Link>
    </>
  )
}

Link태그를 따로 분리하자

원인 ( 2 )

const CustomLink = ({children,url}:ICustomLinkProps) => {
    return (
        <Link href={url}>
          <a>
              {children}
          </a>
        </Link>
    )
}

export default CustomLink;

이 태그도 같은 문제가 발생한다. 원인은 Link컴포넌트는 a태그와 본인 사이에 공백 또한 컴포넌트로 인식하기 때문에 발생한다.

해결 ( 2 )


const CustomLink = ({children,url}:ICustomLinkProps) => {
    return (
        <Link href={url}><a>{children}</a></Link>
    )
}

export default CustomLink;

위와 같이 공백을 모두 없애주자.

profile
I'm beginner

0개의 댓글