猫でもわかるWebプログラミングと副業

本業エンジニアリングマネージャー。副業Webエンジニア。Web開発のヒントや、副業、日常生活のことを書きます。

Next.js で、いい感じに head, title, ogp などを配置する【React.js】

Next.js の Head コンポーネントを使う

Next.js では、 Head コンポーネントを使うことで、 title などの <head> タグ内の属性を設定できます。

import type { NextPage } from 'next';

import Head from 'next/head'

const Home: NextPage<HelpProps> = (props) => {
  return (
    <>
      <Head>
        <title>ページタイトル</title>
        <meta property="og:image" content={ogp画像}/>
        ...
      </Head>
    </>
  )
}

タイトルとかをいい感じに使い回す

Head を拡張して、独自コンポーネント MyHead を定義しておき、各ページでは MyHead を使うようにしておくと便利です。

import type { NextPage } from 'next'
import Head from 'next/head'


interface MyHeadProps {
  title?: string
  thumbnailUrl?: string
  description?: string
}

const MyHead: NextPage<MyHeadProps> = ({title, thumbnailUrl, description}) => {
  const siteName = "サイト名"
  if (title === undefined) {
    title = siteName
  } else {
    title = `${title} - ${siteName}`
  }

  if (thumbnailUrl === undefined) {
    thumbnailUrl = 'https://hoge/fuga.png';
  }

  if (description === undefined) {
    description = "ふがふがふが"
  }

  return (
    <Head>
      <title>{title}</title>
      <meta property="og:title" content={title}/>
      <meta property="og:image" content={thumbnailUrl}/>
      <meta property="og:description" content={description}/>
    </Head>
  )
}

export default MyHead