Post

NextJs에 Chakra UI + Typescript (emotion) 적용

Chara UI

React나 NextJS 등에서 사용할 수 있는 Component Library이다. Emotion을 기반으로 만들어 졌으며, 제일 모던하고 CSS를 많이 사용하지 않아도 될 것 같고, styled-component로 구현했던 것 들은 Emotion으로 충분히 대체 가능하기 때문에 이번 프로젝트에서 styled-component를 걷어내고 사용하게 됐다.

Install

npm

1
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

yarn

1
yarn add @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

Theme / Global 적용

나 같은 경우 먼저 global로 적용할 styles.ts 파일을 먼저 만들어줬다.

styles.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const styles = {
  global: {
    "html, body": {
      margin: 0,
      padding: 0,
    },
    a: {
      textDecoration: "none",
    },
    "*": {
      boxSizing: "border-box",
    },
  },
};

export default styles;

그 다음으론 foundation으로 사용할 폰트, 컬러 등을 지정하였다. color 같은 경우는 charkra 모듈인 theme를 import하여 color를 지정하였다. index로 채도를 조절할 수 있어서 꽤나 요긴했다!

다른 foundation 파일들은 생략하겠다. 코드가 너무 길어져서…

colors.ts

1
2
3
4
5
6
7
8
9
10
11
import { theme } from "@chakra-ui/react";

const primary = theme.colors.teal;
const secondery = theme.colors.gray;
const blue = theme.colors.twitter;

export default {
  primary,
  secondery,
  blue,
};

그리고 마지막으로 component의 기본 스타일을 지정하였다. 아래가 Chakra UI의 Document에서 제공하는 component CustomStyle 포맷이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const ComponentStyle = {
  // 객체의 기본 스타일 정의
  baseStyle: {},
  // 사이즈에 대한 스타일 정의 ("sm", "md", "lg")
  sizes: {},
  // 시각적인 변수에 대한 스타일 정의 ("outline", "solid")
  variants: {},
  // size와 variants에 대한 기본 값 정의
  defaultProps: {
    size: "",
    variant: "",
  },
};

예로 아래와 같이 꾸밀 수 있겠다.

button.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const Button = {
  baseStyle: {
    fontWeight: "bold",
  },
  sizes: {
    xl: {
      h: "56px",
      fontSize: "lg",
    },
  },
  variants: {
    solid: (props) => ({
      bg: props.colorMode === "dark" ? "red.300" : "red.500",
    }),
  },
};

export default Button;

이렇게 나는 크게 Global Foundations Components 구조로 theme를 정의했다.
그럼 이제 CharkProvider에 적용시키기 위한 index.ts가 필요하다. 아래와 같이 필요한 스타일들을 module화 한 뒤 import하여 extendTheme로 export한다.

index.ts

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
import { extendTheme } from "@chakra-ui/react";

// Global style overrides
import styles from "./styles";

// Foundational style overrides
import config from "./foundations/config";
import fonts from "./foundations/fonts";
import colors from "./foundations/colors";
import shadows from "./foundations/shadows";

// Component style overrides
import Button from "./components/button";

const customTheme = {
  styles,
  fonts,
  config,
  colors,
  shadows,
  components: {
    Button,
  },
};

export default extendTheme(customTheme);

이제 export한 theme를 _app.tsx 파일에 Provider 시켜주면 된다.

_app.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ChakraProvider } from "@chakra-ui/react";
import themes from "themes";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <ChakraProvider resetCSS theme={themes}>
        <Component {...pageProps} />
      </ChakraProvider>
    </>
  );
}

export default MyApp;

이제 theme를 정의 한대로 잘 적용되는 것을 볼 수 있다!

그리고 위에 style을 정의할 때 [h, bg] 같이 모르는 style 속성들이 있는데 이건 Chakra 내에서 사용하는 약식 정의다. 링크를 타고 가 확인할 수 있다. ex) h -> height, bg -> background

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