Home Emotion
Post
X

Emotion

Emotion

HTML 요소 혹은 React 컴포넌트에 CSS를 적용하기 위한 라이브러리입니다.

CSS-in-JS 라이브러리 중에서는 Styled Component 라이브러리가 가장 대두 되었으나, MUI(Material UI)가 스타일링 엔진을 Emotion으로 채택하면서 이목이 집중되고 있습니다.


Emotion의 장점

  • className 자동 부여
  • 재사용 가능
  • props, 조건 등에 따른 스타일 지정 가능
  • vendor-prefixing, nested selectors, media queries 등이 적용되어 작성이 간편함
  • styled component 사용방식과 css prop 기능을 지원하여 확장에 용이
  • styled component보다 파일 사이즈가 작고, SSR(서버 사이드 랜더링)시 서버 작업 불필요

JSX Pragma

먼저 Pragma컴파일러에게 파일을 어떻게 해석할 지 알려주는 것을 말합니다.

예시로는 JavaScript에서 “use strict”를 상단에 작성할 시, Strict Mode로 해석됩니다.

JSX Pragma는 Babel 트랜스파일러에게 JSX 코드를 변환할 때, React의 jsx() 함수가 아닌 Emotion의 jsx() 함수를 사용하라고 알려주기 위한 Pragma입니다.

작성해주지 않으면 css prop에 넘어간 스타일이 반영이 안될 수 있습니다.

  • React v16 이상의 버전

    1
    
    /** @jsxImportSource @emotion/react */
    
  • React v16 이하의 버전

    1
    2
    
    /** @jsx jsx */
    import {css, jsx} from '@emotion/react";
    

@emotion/css

@emotion/css 패키지프레임워크에 상관없이 Emotion을 사용할수 있는 패키지입니다.

Babel, config 변경 등의 추가적인 세팅없이 자동으로 벤더프리픽스를 지원하고, 중첩 선택자, 미디어 쿼리를 지원합니다.

  • 설치

    1
    
    npm i @emotion/css
    

사용방법

  • css 함수

    Styled Components의 styled() 함수처럼 Emotion의 대표적인 함수입니다.

    css() 함수의 반환 결과를 해당 스타일을 적용하고 싶은 HTML 요소나 React 컴포넌트의 css라는 prop에 넘겨주어 작동합니다.

    문자열 방식과 객체 방식으로 사용할 수 있습니다.

    현재는 Styled Components에서 css() 함수를, Emotion에서 styled() 함수를 제공하고 있습니다.

    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
    
    /** @jsxImportSource @emotion/react */
    import { css } from "@emotion/css";
    
    const color = "white";
    
    // String Style
    render(
      <div
        css={css`
          background-color: hotpink;
          &:hover {
            color: ${color};
          }
        `}
      >
        This has a hotpink background.
      </div>
    );
    
    // Object Style
    render(
      <div
        css={css({
          backgroundColor: "hotpink",
          "&:hover": {
            color,
          },
        })}
      >
        This has a hotpink background.
      </div>
    );
    

@emotion/react

@emotion/react 패키지는 React를 사용할 때 권장되는 패키지입니다.

Vanilla Js 프로젝트에서는 @emotion/css 패키지를 사용하고 React 프로젝트에서는 @emotion/react 패키지를 사용하면 됩니다.

사용방법은 동일합니다.

  • 설치

    1
    
    npm i @emotion/react
    

@emotion/styled

@emotion/styled 패키지를 사용하면 Styled Components의 styled() 함수처럼 사용할 수 있습니다.

  • 설치

    1
    
    npm i @emotion/styled
    

사용방법

css 함수와 같이 문자열과 객체 형태 모두 지원합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/** @jsxImportSource @emotion/react */
import styled from "@emotion/styled";

// String Style
const Button = styled.button`
  color: ${(props) => (props.primary ? "hotpink" : "turquoise")};
`;

// Object Style
const Container = styled.div((props) => ({
  display: "flex",
  flexDirection: props.column && "column",
}));

render(
  <Container column>
    <Button>This is a regular button.</Button>
    <Button primary>This is a primary button.</Button>
  </Container>
);
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.