javascriptreactjsnext.js

How to set document's title per page?


I am using the pages/_document.js hook to add Bootstrap and jQuery to my pages, by the way I set the <Head>

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head>
          <title>Default title</title>
          <link rel="stylesheet" href="/static/lib/bootstrap3/css/bootstrap.min.css" />
        </Head>

        <body>
          <Main/>
          <NextScript/>
          <script src="/static/lib/jquery3/jquery-3.3.1.min.js" />
          <script src="/static/lib/bootstrap3/js/bootstrap.min.js" />
        </body>
      </html>
    )
  }
}

Now, I would like to set a different title for my pages. Is it possible to used <Head> outside of Document? I mean in <div> like this:

const ContactPage = () => {
  return (
    <div>
      <Head>
        <title>You better contact us!</title>
      </Head>

      <div className="page-body">...</div>
    </div>
  )
}

And if possible, will it overwrite or merge what is already set in pages/_document.js?


Solution

  • You want to use the next/head component:

    import Head from 'next/head'
    
    export default () =>
      <div>
        <Head>
          <title>My page title</title>
          <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        </Head>
    
        <p>Hello world!</p>
      </div>
    

    See the docs: https://nextjs.org/docs/api-reference/next/head