カスタムDocument
カスタム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
は現在、Next.jsのデータフェッチメソッド、例えばgetStaticProps
やgetServerSideProps
をサポートしていません。
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
が追加されています。
お役に立ちましたか?