LoginSignup
1
0

More than 1 year has passed since last update.

[Next.js]styled-componentsのスタイルが適用されない時の対処

Last updated at Posted at 2021-12-18

Next.jsでstyled-componentsが適用されない

先日、Next.jsでstyled-componentsを使おうと思い作成していたら
困ったことに更新された直後などしか、スタイルが当たらない現象がありました。
最初は、何かミスったかなと思い、色々みていましたが
全く関係なく、設定が必要だったのです!

この設定はすぐにできます!

設定内容

現在では.tsxが主流かなと思っているので、そちらのものを記載します。
作成箇所はpages配下に
ファイル名:_document.tsx
です。

_document.tsx
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    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();
    }
  }
}

コピペでOKです。

こちらでスタイルが当たるようになります。

最後に

閲覧ありがとうございます。
皆さんのお役に立つと嬉しいです。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0