next.jsではhtmlのheadタグの中にmetaタグなど色々を出力したい場合はnext/headコンポーネントを利用する。
使い方
Headのchildrenが動的にheadタグに入る。
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
重複をなくす
一意的なkeyを設定すると、後勝ちで1つのみが適応される。
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
上記レンダリングの結果にはMy new title
が出力される
<html>
<head>
<meta property="og:title" content="My new title" />
</head>
...