カスタムドキュメント
カスタム `Document` は、ページのレンダリングに使用される `<html>` タグと `<body>` タグを更新できます。
デフォルトの `Document` をオーバーライドするには、以下に示すように `pages/_document` ファイルを作成します。
pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
知っておくと良いこと:
- `_document` はサーバーでのみレンダリングされるため、`onClick` などのイベントハンドラはこのファイルでは使用できません。
- ページが正しくレンダリングされるためには、`<Html>`、`<Head />`、`<Main />`、`<NextScript />` が必要です。
注意点
- `_document` で使用される `<Head />` コンポーネントは、`next/head` とは異なります。ここで使用される `<Head />` コンポーネントは、すべてのページに共通の `<head>` コードにのみ使用してください。`<title>` タグなど、その他すべての場合には、ページまたはコンポーネントで `next/head` を使用することをお勧めします。
- `<Main />` の外部にある React コンポーネントは、ブラウザによって初期化されません。ここにアプリケーションロジックやカスタム CSS ( `styled-jsx` など) を追加しないでください。すべてのページで共有コンポーネント (メニューやツールバーなど) が必要な場合は、代わりにレイアウトを参照してください。
- `Document` は現在、`getStaticProps` や `getServerSideProps` などの Next.js データフェッチメソッドをサポートしていません。
`renderPage` のカスタマイズ
`renderPage` のカスタマイズは高度な操作であり、CSS-in-JS などのライブラリがサーバーサイドレンダリングをサポートするためにのみ必要です。組み込みの `styled-jsx` サポートには必要ありません。
**このパターンの使用はお勧めしません。** 代わりに、App Routerを段階的に導入することを検討してください。App Routerを使用すると、ページとレイアウトのデータをより簡単にフェッチできます。
pages/_document.tsx
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
DocumentInitialProps,
} from 'next/document'
class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const originalRenderPage = ctx.renderPage
// Run the React rendering logic synchronously
ctx.renderPage = () =>
originalRenderPage({
// Useful for wrapping the whole react tree
enhanceApp: (App) => App,
// Useful for wrapping in a per-page basis
enhanceComponent: (Component) => Component,
})
// Run the parent `getInitialProps`, it now includes the custom `renderPage`
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
知っておくと良いこと:
- `_document` の `getInitialProps` は、クライアントサイド遷移中には呼び出されません。
- `_document` の `ctx` オブジェクトは、`getInitialProps` で受信されるオブジェクトと同等ですが、`renderPage` が追加されています。
これは役に立ちましたか?