React.js

[Next.js] Next 에서 Styled-componets 사용시 번쩍임 현상

★개발일기★ 2023. 4. 28. 15:36
반응형

 

Next.js 에서 styled-componets 를 그냥 사용하게 되면 className did not match 경고가 뜨고,
css 가 적용이 되지 않은 상태로 번쩍임 현상이 일어난다.

이는 Next.js 에서는 최초 페이지는 SSR 되는데, 이 때 styled-components 의 CSS 가 Head 에 주입되게 해줘야한다.

 

1. nextConfig 에 styledcomponents 설정 할 것

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true
  }
}

module.exports = nextConfig

 

2. _document Head 에 style 을 주입시켜 줄 것

import Document, {
  Html,
  Head,
  Main,
  NextScript,
  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();
    }
  }

  render() {
    return (
      <Html>
        <Head>
          <style />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

 

위 두 사항을 적용 후에 오류가 해결됬는지 확인해보자.


P.S 서치하다보면 babel-plugin-styled-components 를 install 해서 .babelrc 파일을 작성을 요하는 정보가 있는데,
       Next.js 12 이후로는 babel 대신 swc 를 컴파일 하도록 변경되어서, 위의 1번을 작업해주면 동일하게 해결이 된다.

반응형