NextJS API: next/head

hwisaac·2023년 3월 13일
0

NextJS API(page router)

목록 보기
9/10

우리는 페이지 head에 요소를 추가하기 위한 내장된 컴포넌트를 노출합니다:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

head에서 중복된 태그를 피하려면 key 속성을 사용할 수 있습니다. 이렇게 하면 태그가 한 번만 렌더링되도록 보장합니다. 다음 예제와 같이:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta property="og:title" content="My page title" key="title" />
      </Head>
      <Head>
        <meta property="og:title" content="My new title" key="title" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

이 경우 두 번째 <meta property="og:title" />만 렌더링됩니다. 중복된 key 속성을 가진 meta 태그는 자동으로 처리됩니다.

head의 내용은 컴포넌트가 unmount될 때 지워지므로 각 페이지가 head에 필요한 것을 완전히 정의하고 다른 페이지에서 추가한 것에 대해 가정하지 않도록 주의해야 합니다.

title, meta 또는 다른 요소 (예: script)는 Head 요소의 직접적인 자식 또는 최대 하나의 <React.Fragment> 또는 배열로 포함되어 있어야 합니다. 그렇지 않으면 태그가 클라이언트 사이드 탐색에서 올바르게 선택되지 않습니다.

next/head에서 수동으로 <script>를 만드는 대신 컴포넌트에서 next/script를 사용하는 것이 좋습니다.

0개의 댓글