how to use <Head> with nextJS
Asked Answered
D

2

4

I'm having problems getting mobile metatags into a nextJS app. According to the docs here, this should work https://nextjs.org/docs#populating-head

But I don't see the title or any of my own meta properties getting rendered. All I see is:

<!DOCTYPE html><html><head><meta charSet="utf-8" class="next-head"/>

which looks like some type of default.

import Link from 'next/link'
import Head from 'next/head'
import Header from '../components/Header'
import BaseLayout from '../components/BaseLayout.js'

const Index = () => (
  <BaseLayout>
    <Head>
      <title>HSK App</title>
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>
    <Link href='/quizList'>
      <h3>HSK Quiz App!</h3>
    </Link>
  </BaseLayout>
)
export default Index

Help appreciated!

Deiform answered 24/2, 2019 at 21:1 Comment(0)
T
1

NextJS's <Head> component seems a bit buggy.

For one thing, two <Head> tags set in different components sometimes will interfere with each other in really bizarre ways. For another, sometimes having it in page components works, sometimes it doesn't. And the rules seems perfectly random.

The only thing that consistently worked for me is using <Head> in _document.js. :/

Thiol answered 26/11, 2019 at 1:56 Comment(2)
Just a note on this that using <Head> in _document.js isn't supported anymore. There's an explicit warning to avoid it, and you should instead use it in _app.js if you need to set global tags.Mali
maybe use the key='xyz' attribute. This force to add the given tag only once in the header.Gangplank
N
0

I can't reproduce this problem. Maybe a bug was fixed since this question was written, but the documentation does point out they use a key attribute to help Next.js keep track of meta tags and eliminate duplicates when they appear in parent and child elements.

To avoid duplicate tags in your head you can use the key property, which will make sure the tag is only rendered once, as in the following example:

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
Nabonidus answered 27/5, 2020 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.