Next.jsでstyled-componentsを使うときに最初に設定しておくこと
Next.jsでstyled-componentsを使うとスタイルがあたっていない状態になることがあるので,しっかりと準備していきます.(これもっとはやく知りたかった)
styled-componentsをインストール
TypeScriptに対応できるように型もインストールしておく
yarn add styled-components @types/styled-components
styled-componentsのスタイルが当たらない問題に対処
スタイルが当たらない現象がおこるのはstyled-componentsの公式に対処方法が書いてあった.
https://styled-components.com/docs/advanced#nextjs
_document.tsx
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
これのファイルをpageディレクトリ内に作成すればOKと書いてます.
renderPage()ってメソッドを使っていい感じにしてくれるみたい.
DAIBUIIKANJI
【参考文献・参考記事など】