styled-components 오류(next.js 리렌더링 시 styled-component 미적용)

개발공부·2022년 10월 25일
0

CSS

목록 보기
2/4

* 원인 : styled-components 적용 시 렌더링 될 때마다가 적용되지 않음

▶ 아무 조치 없이 Next.js에서 styled-components 적용 시 일정 시간이 지난 후에 스타일 적용(바로 적용되지 않아 원하는 모습으로 작업하는 것에 어려움 겪음)
▶ Next.js는 모든 페이지가 Pre-Render 되기 때문
▶ Pre-Render은 Initial Load Stage | Hydration Stage 존재
▶ Initial Load Stage : Static하게 생성된 HTML 렌더링 된 후, Hydration Stage에서 나머지 JS 파일 로드

* 출처(csr, ssr, ssg 비교) : https://wonit.tistory.com/369
▶ CSR(Client Side Rendering) : 화면을 클라이온트단에서 바꾸는 기법
▶ SSR(Server Side Rendering) : 화면을 서버단에서 전송해주는 기법
▶ SSG(Server Side Generation) : 화면을 서버에서 미리 만들어 전송해주는 기법

* 결론 : Next.js는 SSR 혹은 SSG를 기본으로 사용해서 Pre-Rendering하면서 Initial Load 과정에서 미리 HTML을 로드하고 Hydration 과정에서 다른 파일을 로드 하기 때문

  • 해결방법 : renderPage 함수 사용
    ▶ 단, 이 방법은 CSS-in-js 라이브러리를 사용할 때만 사용하라고 권장
  • 방법
  • pages._document.js 파일 생성
  • ServerStyleSheet 함수 : styled-components를 import해서 Global하게 설정
  • renderPage 함수로 렌더링 조건 커스텀마이징

[pages._document.js ]

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();
    }
  }
}
profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글