【設定方法】Next.jsでタイトルやメタタグやOGPなどのHeadタグを動的に設置するサンプル

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Next.jsでHeadタグの設定について
よく使用するが毎回調べたりしていたためメモします。
Typescriptにて記述しています。
環境
- React 16.3.2
- Next.js 5.1
- typescript 2.8.3
サンプルコード
ディレクトリ構成
markdown├── components
│ └── head.tsx
└── page
├── index.tsx
└── item.tsx
next/head
をインポートしHead
タグで囲ってあげると
ヘッド要素を展開してくれます。
components/head.tsximport * as React from 'react';
import Head from 'next/head';
interface Props {
title: string;
description: string;
keyword: string;
image: string;
url: string;
}
export default ({ title, description, keyword, image, url }: Props): JSX.Element => {
return (
<Head>
<title>{title}</title>
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta name="keywords" content={keyword'} />
<meta property="og:type" content="blog" />
<meta property="og:url" content={url} />
<meta property="og:image" content={image} />
<meta property="og:site_name" content={title} />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@tcr_jp" />
<meta name="twitter:url" content={image} />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={image} />
<link rel="canonical" href={url} />
<link rel="shortcut icon" href={'https://t-cr.jp/favicon.ico'} />
<link rel="apple-touch-icon" href={'https://t-cr.jp/logo.png'} />
</Head>
);
};
作成したcomponents/head.tsx
をインポートします。
インポートしたHead
を記述する場所についてはどこに記述しても問題ありません。
子コンポーネントに設置することもできます。
page/index.tsx
import * as React from 'react';
import Head from 'components/head';
class App extends React.Component {
public render(): JSX.Element {
return (
<div>
<Head
title={'タイトル'}
description={'ディスクリプション'}
keyword={'キーワード'}
image={'https://t-cr.jp/img.jpg'}
url={'https://t-cr.jp'}
/>
コンテンツ
</div>
);
}
}
export defualt App;
他のページから同じように設定することで
ページごとにデータを渡して動的に設置することが可能です。
page/item.tsx
import * as React from 'react';
import Head from 'components/head';
class Item extends React.Component {
public render(): JSX.Element {
return (
<div>
<Head
title={'タイトル'}
description={'ディスクリプション'}
keyword={'キーワード'}
image={'https://t-cr.jp/img.jpg'}
url={'https://t-cr.jp'}
/>
コンテンツ
</div>
);
}
}
export defualt Item;
- review
今の自分に満足していますか?『持たざる者の逆襲 まだ何者でもない君へ』溝口勇児
- review
ついに語られた業界の裏側!『フジテレビの正体』堀江貴文が描くテレビ局の本当の姿
- review
愛する勇気を持てば人生が変わる!『幸せになる勇気』岸見一郎・古賀史健のアドラー実践編で真の幸福を手に入れる
- review
週末を変えれば年収も変わる!『世界の一流は「休日」に何をしているのか』越川慎司の一流週末メソッド
- review
新しい自分に会いに行こう!『自分の変え方』村岡大樹の認知科学コーチングで人生リセット
- review
科学革命から AI 時代へ!『サピエンス全史 下巻』ユヴァル・ノア・ハラリが予見する人類の未来