[Next.js] styled-components and next.js

Growing_dev·2023년 3월 28일
0

Next.js

목록 보기
2/5

NextJS는 기본적으로 페이지를 SSR을 이용해 pre-rendering한다. Server Side에서 html 파일을 구성하여 브라우저 측에 전달해 렌더링한다.(CSS도 렌더링됨) 이후 JS 파일이 로드되어 자바스크립트 코드가 적용된다.

개발하는 도중 스타일드컴포넌트를 적용 했는데 랜더링 될때 css가 적용 안된 html이 먼저 보였다가 렌더링이 되는 현상이 발견되었다. 그래서 찾아보니 아래와 같은 내용이 나왔다.

CSS-in-JS와 Pre-Rendering
자바스크립트 코드가 적용이 되지 않은 페이지가 미리 렌더링되기 때문에 CSS-in-JS로 스타일링을 하면 스타일이 적용되지 않은 html 코드가 먼저 렌더링되는 문제가 발생하게 된다.

Next.js 공식문서

_document.tsx

import Document, { DocumentContext, DocumentInitialProps } from "next/document";
import { ServerStyleSheet } from "styled-components";

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

적용하였더니 css가 적용된 컴포넌트로 렌더링이 잘되었다.

profile
github ( https://github.com/sktjgudals ) gitlab ( https://gitlab.com/sktjgudals10 )

0개의 댓글