Javascript/Next

[NextJS] Syled-components 사용하는 방법

eulBlue 2023. 8. 17. 00:19

📱테스트 환경

"react": "18.2.0"
"react-dom": "18.2.0"
"typescript": "^5.1.6"

😢 내가 겪은 문제

개발환경 ( http ) 에서는 문제가 없었는데 배포환경 ( https ) 에서는 한번씩 디자인이 깨졌다.

아니면 새로고침 했을 때 디자인이 깨져있다가 원상복구되는 현상을 겪었었다.

해결방법을 찾아보니, .babelrc 를 이용하여 해결하는 방법은 되게 많이 설명되었는데, NextJS 11 버전부터는 비권장 하는 방법이다.

그래서 열심히 정보를 찾아봐서 하는 방법을 찾아서 기록해두려고 한다. 언제나 복사 + 붙여넣기 하면 사용할 수 있도록.

먼저 stlyed-components 를 추가해준다. 나는 NextJS + Typescript 환경이니까 설치

npm install @types/styled-components

next.config.js

const nextConfig = {
  ...
  compiler: {
    styledComponents: true,
  },
  ...
};

 

_document.tsx

import { ServerStyleSheet } from "styled-components";

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const initialProps = await Document.getInitialProps(ctx);
    const originalRenderPage = ctx.renderPage;
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      return {
        ...initialProps,
        styles: [initialProps.styles, sheet.getStyleElement()],
      };
    } finally {
      sheet.seal();
    }
  }

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

이렇게 해주면 설정은 끝난다 !! 이후에는 이제 import 해서 사용하면 된다 !!

import styled from "styled-components";
export const Body = styled.div`
  text-align: center;
  width: 100%;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
`;

이런식으로 사용하면 된다.

.babelrc 를 이용해서 하던 것보다 훨씬 간편하고 쉽게 사용할 수 있게 변한것 같다.

나는 개인적으로 바벨을 사용하던 때보다 지금이 간편하고 좋다.