[Next.js] 새로고침 시 styled-components 적용 안되는 문제 - 1

LIMHALIM·2023년 11월 23일
0

나는 CSS 라이브러리로 tailwindstyled-components를 같이 사용하는데, styled-components는 따로 SSR 세팅을 안해주면 서버사이드 렌더링이 안 되므로, 동적으로 스타일 태그를 생성하기 때문에 서버사이드랜더링(SSR) 프레임워크 새로고침 시 style이 적용되기 전에 렌더링되어버린다고 한다.

해결 방법으로 다들 .babelrc 파일을 생성하라고 했지만 next/font 어쩌고 오류로 이 파일을 무조건 제거해야만 했고..
(+ 2024.01.24, SWC로 전환하는 새로운 해결 방법을 확인해주세요!)

그러다가 pages 경로에 기본적으로 존재하는 _document.tsx 파일을 수정해주는 방법으로 해당 문제를 해결할 수 있었다!


Before

_document.tsx

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

위 기존 파일에서 아래와 같이 수정해준다.

After

_document.tsx

import React from "react";
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 />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

위 처럼, 파일만 수정해줌으로써 새로고침해도 styled-components로 적용한 스타일이 잘 적용된 것을 볼 수 있다 :)

profile
모든 익숙함에 물음표 더하기

0개의 댓글