티스토리 뷰

 

리액트와 next를 사용하여 SSR 적용 중 className 오류가 났다.

원인은 nextjs 사용시 css 마찬가지로 SSR 렌더링도 먹여줘야 하는것이었다.

 

"styled components는 따로 SSR 세팅(_document.js)을 안 하면 서버사이드 렌더링이 안 되므로 동적으로 스타일 태그를 생성하기 때문입니다.

기본적으로 next의 pages는 서버사이드 렌더링이 된다.

getServerSideProps는 추가적으로 데이터까지 가져오는 것이고, ssr을 제외한 상황에서는 모두 styled-components가 동작한다"

 

 

 

 

그럼 SSR을 적용해 보자!

주의할 점은 getInitialProps는 주로 사용 안 하고 Document에서만 사용한다는 점 꼭 이억하자.

 

_document.js 기본 형태

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

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

 

 

추가적으로

CSS가 SSR이 적용되는지 확인하는 방법은 

 

shortcuts에서 javascript를 비활성화 시켜준 후 사이트를 새로고침 해보면 알 수 있다 !