Emotion : 설치 및 정리

Yunseok Choi·2024년 3월 27일

Nextjs에서 Emotion 사용하는 법

1.설치

npm install @emotion/react
  1. 페이지 컴포넌트에 써야할 것들

    • /** @jsxImportSource @emotion/react */
      • jsx프레그마를 추가시켜야 함. ⇒ dev 트랜스파일러한테 jsx코드를 변환할 때 리액트의 jsx함수를 사용하지 말고, Emotionjsx함수를 사용하라는 뜻
    • “use client”
      • 위의 것을 추가하려면 client모드로 변환시켜야 한다.(최상단에 써야됨)
  2. tsconfig.json 파일 수정

    {
      "compilerOptions": {
        "types": ["@emotion/react/types/css-prop"], // add this line
        ...
      }
    }

    compilerOptionstypes줄을 추가시키면, 태그 안의 css옵션에 그어졌던 css속성이 없다고 뜨는 오류를 없앨 수 있다.


전역(바디, 등등)에 스타일링 주는 법

"use client";
/** @jsxImportSource @emotion/react */
import { Global } from "@emotion/react";
import { globalStyles, flexCenterX2, fullWidthHeight } from "./globalStyles";

export default function Home() {
  return (
    <>
      <Global styles={globalStyles} />
      <p css={[flexCenterX2, fullWidthHeight]}>
        <span>Welcome to</span>
      </p>
    </>
  );
}
import { css } from "@emotion/react";

export const globalStyles = css `
body {
  width: 100%;
  height: 100vh;
  padding: 0;
  margin: 0;
  color: white;
  background-color: black;
}`

@emotion/react에서 지원하는 Global 태그를 쓰면 됨. 이 태그에 styles옵션을 주고 위에 나오는 것처럼 백틱(`) css변수를 주면 그 스타일링이 적용됨. 여기서p, h1`태그같은 것들도 기본 스타일링이 가능.
=> 근데 페이지별로 넣어야 함.. 그래서 필자는 그냥 index.css를 사용해서 전역스타일링을 사용하였다.

profile
이용자와 서비스를 하나로 만드는 개발자, Hermann입니다.

0개의 댓글