Post

NextJs styled-component 적용하기

Next 프로젝트를 Sass로 진행하다가 CSS-in-JS로 변경하려 한다. (클래스명 짓기가 너무 힘들다..ㅜㅜ) 또한, jsx에서 사용하는 js값을 css내에서 사용해서 유연하게 사용할 수 있더라… 그리고 클래스가 필요한 부분에선 NextJS에서 지원하는 css모듈 ([name].moudle.css)을 사용하여 해당 페이지에서만 사용할 생각이다.

Next JS 에서 CSS-in-JS 적용하기

styled-component

이건 라이브러리라서 먼저 npm으로 다운 받아야한다. 나는 typescript를 사용하기 때문에 type을 붙였다.

1
npm i type@styled-components

SSR과 CSR의 생성 해시값이 일치하지 않아 오류가 뜨기 때문에 babel plugin을 다운받아서 세팅해준다.

npm i babel-plugin-styled-components -D

그리고 babel 세팅 파일을 만들어준다.

.babelrc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
    "presets": [
        "next/babel"
    ],
    "plugins": [
        [
            "styled-components",
            {
                "ssr": true,
                "displayName": true,
                "preprocess": false
            }
        ]
    ]
}

그리고 _document.tsx 파일을 생성해준다. 이 파일은 NextJS에서 head, body 부분을 Custom 할 수 있게 지원하는 파일이다. 이 부분을 세팅하지 않으면 SSR렌더링 시에 styled가 주입되지 않아 꼭!! 해줘야한다.

document.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, { ReactElement } from "react";
import Document, { Html, Head, Main, NextScript, DocumentInitialProps, DocumentContext } from 'next/document';
import { ServerStyleSheet } from "styled-components";

// NEXT.JS CUSTOM DOCUMENT
// https://nextjs.org/docs/advanced-features/custom-document

export default class MyDocument extends Document {
  
  static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    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(): ReactElement {
    return(
      <Html lang="en">
        <Head>
          // 이곳엔 폰트 혹은 meta 태그를 넣을 수 있다.
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

자 다 됐다. 이제 화면에서 사용한다면 요렇게 Layout을 세팅하여 사용하면 된다~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import styled from "styled-components";

const Layout = ({ children }: Props): JSX.Element => {
  return (
    <>
      <Container>
        <NavBar />
        <Content>{children}</Content>
        <footer>
          <Footer />
        </footer>
      </Container>
    </>
  );
};

const Container = styled.div`
  display::flex;
  justify-contents:center;
  flex-direction:column;
  min-height:100vh;
`;

const Content = styled.div`
  display: flex;
  flex: 1;
`;

This post is licensed under CC BY 4.0 by the author.