Emotion - 프로젝트에 이모션 도입하기 (CRA 프로젝트)

중고신입개발자·2022년 2월 7일
0

이모션

설치

yarn add @emotion/react
npm install --save @emotion/react

1. css Prop


0. 사전설정 : JSX Pragma(JSX 컴파일 지시자)를 사용하기

css prop를 사용하는 원본파일에 jsx pragma를 설정한다. 이 방법은 css props를 테스트하거나 바벨 config를 구성할 수 없는 cra or codesandbox에 적합하다.

/** @jsx jsx */

CRA4 버전에서는 /** @jsx jsx */ 대신 /** @jsxImportSource @emotion/react */ 를 사용한다

만약에 jsx pragma를 설정하지 않는다면 css prop의 값은 [Object Object]를 렌더한다.

1. Oject Style

css prop은 object style로 사용할 수 있다.

/** @jsx jsx */
import { jsx } from '@emotion/react'

render(
  <div
    css={{
      backgroundColor: 'hotpink',
      '&:hover': {
        color: 'lightgreen'
      }
    }}
  >
    This has a hotpink background.
  </div>
)

2. String style

/** @jsx jsx */
import { css, jsx } from '@emotion/react'

const color = 'darkgreen'

render(
  <div
    css={css`
      background-color: hotpink;
      &:hover {
        color: ${color};
      }
    `}
  >
    This has a hotpink background.
  </div>
)

3. Style Precedence

  • className prop은 emotion styles의 css prop에 오버라이딩 된다.
  • emotion style이 아닌 클래스네임은 무시되고 계산된 이모션 클래스 네임이 추가된다.
/** @jsx jsx */
import { jsx } from '@emotion/react'

const P = props => (
  <p
    css={{
      margin: 0,
      fontSize: 12,
      lineHeight: '1.5',
      fontFamily: 'sans-serif',
      color: 'black'
    }}
    {...props} // <- props contains the `className` prop
  />
)

const ArticleText = props => (
  <P
    css={{
      fontSize: 14,
      fontFamily: 'Georgia, serif',
      color: 'darkgray'
    }}
    {...props} // <- props contains the `className` prop
  />
)

const SmallArticleText = props => (
  <ArticleText
    css={{
      fontSize: 10
    }}
    {...props} // <- props contains the `className` prop
  />
)
.css-result {
+ margin: 0;
- font-size: 12px;
+ line-height: 1.5;
- font-family: 'sans-serif';
- color: black;
- font-size: 14px,
+ font-family: Georgia, serif,
+ color: darkgray;
+ font-size: 10px;
}
profile
취업전에는 기술스택을, 취업후에는 고도화를 하자

0개의 댓글