[Next.js] Next에서 styled-components 적용하기!

지혜의 Devlog 📚·2021년 11월 22일
0
post-thumbnail

이번 포스팅은 Next.js에 styled-components를 적용할 때 가장 기본적인 설정 2가지를 정리해보려 한다.

  1. style 적용 전 렌더되는 에러 해결법
  2. GlobalStyle 적용 방법

style 적용 전 렌더되는 에러 해결법

Next.js로 프로젝트를 구성하는 도중, styled-components를 적용하여도 새로고침하면 css가 풀리는 현상을 마주하였다..! 😬
현상의 이유는 Next.js가 SSR로 작동하기 때문에 style이 들어가기도 전에 렌더링이 되는 것이다.
따라서 아래의 방법으로 쉽게 SSR 단계에서 CSS를 적용할 수 있다.


  1. babel-plugin 설치
npm i babel-plugin-styled-components -D

  1. 루트 디렉토리에 .babelrc를 생성한다.
{
  "presets": ["next/babel"],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}

  1. pages폴더에 _documents.js를 생성하여 하기 코드를 붙여넣는다.
// _documents.js
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>
          <style />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

GlobalStyle 적용 방법

전역 CSS 적용은 대체로 React와 동일하다.


  1. createGlobalStyle를 사용하여 GlobalStyle를 생성한다.
// reset.js
import { createGlobalStyle } from 'styled-components';

export const GlobalStyle = createGlobalStyle`
  body {
  	background: #000;
  }
`

  1. _app.js에 GlobalStyle을 적용시킨다.
// _app.js
import GlobalStyle from 'styles/reset';

function MyApp({ Component, pageProps }) {
  return (
    <>
      <GlobalStyle />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

위 두가지 방법으로 styled-components를 next.js에 기본적으로 설정해야하는 것을 알아보았다. 👏

0개의 댓글