Emotion

오늘은 Emotion에 대해 소개해드리겠습니다 !

Emotion의 장점 🌟

  • css-in-js 형식으로 스타일을 사용할 수 있다.
  • className이 자동으로 부여되기 때문에 스타일이 겹칠 염려가 없다.
  • 재사용이 가능하다.
  • props, 조건 등에 따라 스타일을 지정 가능하다.
  • vendor-prefixing, nested selectors, and media queries 등이 적용되어 작성이 간편하다. ( 알기 쉽게 반응형 이라고 생각하시면 됩니다 :) )
  • styled component 사용방식과 css prop 기능을 지원하여 확장에 용이하다. ( 앱에서는 styled component를 많이 사용하지만 웹에서는 prop 기능때문에 Emotion을 많이 사용하는 것 같습니다. 개발자 차이이지만 css, scss를 사용하거나 styled component, emotion등을 사용 하는 것은 개발자 차이입니다! )
  • styled component보다 파일 사이즈가 작고, ssr시 서버 작업이 필요없다. ( ssr 이란 서버사이드 랜더링입니다!) 서버사이드랜더링 플로우 입니다

사용법 📘

css prop

import { css } from '@emotion/react'

const color = 'white'

render(
  <div
    css={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

composition

import { css } from '@emotion/react'

const danger = css`
  color: red;
`const base = css`
  background-color: darkgreen;
  color: turquoise;
`render(
  <div>
    <div css={base}>This will be turquoise</div>
    <div css={[danger, base]}>
      This will be also be turquoise since the base styles
      overwrite the danger styles.
    </div>
    <div css={[base, danger]}>This will be red</div>
  </div>
)

styled component

import styled from '@emotion/styled'

const Button = styled.button`
  padding: 32px;
  background-color: hotpink;
  font-size: 24px;
  border-radius: 4px;
  color: black;
  font-weight: bold;
  margin-bottom: ${props => props.value ? '4px' : '2px'}
  &:hover {
    color: white;
  }
`render(<Button>This my button component.</Button>)

Object styles

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      color: 'darkorchid',
      backgroundColor: 'lightgray'
    }}
  >
    This is darkorchid.
  </div>
)

import styled from '@emotion/styled'

const Button = styled.button(
  {
    color: 'darkorchid'
  },
  props => ({
    fontSize: props.fontSize
  })
)

render(
  <Button fontSize={16}>
    This is a darkorchid button.
  </Button>
)

Child Selectors

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      color: 'darkorchid',
      '& .name': {
        color: 'orange'
      }
    }}
  >
    This is darkorchid.
    <div className="name">This is orange</div>
  </div>
)

media Queries

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      color: 'darkorchid',
      '@media(min-width: 420px)': {
        color: 'orange'
      }
    }}
  >
    This is orange on a big screen and darkorchid on a small
    screen.
  </div>
)

Reusable Media Queries

import {  css } from '@emotion/react'

const breakpoints = [576, 768, 992, 1200]

const mq = breakpoints.map(
  bp => `@media (min-width: ${bp}px)`)

render(
  <div>
    <div
      css={{
        color: 'green',
        [mq[0]]: {
          color: 'gray'
        },
        [mq[1]]: {
          color: 'hotpink'
        }
      }}
    >
      Some text!
    </div>
    <p
      css={css`
        color: green;
        ${mq[0]} {
          color: gray;
        }
        ${mq[1]} {
          color: hotpink;
        }
      `}
    >
      Some other text!
    </p>
  </div>
)

numbers

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      padding: 8,
      zIndex: 200
    }}
  >
    This has 8px of padding and a z-index of 200.
  </div>
)

fecepaint

npm i facepaint

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

const breakpoints = [576, 768, 992, 1200]

const mq = facepaint(
  breakpoints.map(bp => `@media (min-width: ${bp}px)`)
)

render(
  <div
    css={mq({
      color: ['green', 'gray', 'hotpink']
    })}
  >
    Some text.
  </div>
)

내가 느낀 장, 단점 😎

장점

혼자 프론트엔드를 개발하고 스타일을 주려면 Emotion을 쓰는 것이 훨씬 편할 겁니다. 왜냐하면 엘리멘트 태그들을 자기 마음대로 커스터마이징 할 수 있고 자기가 작성한 태그니까 알기가 쉬울 것 이라고 생각합니다 🙂

단점

다른 개발자 분이 코드를 봤을 때 2번 일을 해야하는 경우가 있을 수 있습니다. div라는 태그를 바꾸고 싶은데 실제 퍼블리싱 코드에는 div가 없어서 div emotion 코드를 찾아서 변경을 해줘야하는 부분이 단점? 불편한점 이라고 생각합니다. 그리고 엘리먼트 태그들은 많아질 수록 가독성이 떨어진다는 부분이 저에게는 단점으로 느껴졌습니다. 😢

결론

일단은 Emotion으로 되어있는 코드들을 보고 유지보수에 최대한 힘을 쓰는 것이 첫 번째 라고 생각합니다. 물론 다른 스타일 라이브러리나 css 등은 보기 쉽겠지만 조금은 더 시간을 들여야 하지 않나, 이 시간을 최대한 줄이자 라는 마음으로 개발해야 할 것 같습니다. 그리고 조금씩 익숙해지면 바로바로 적응이 가능할 것 같습니다 😊

'React' 카테고리의 다른 글

상태 관리 라이브러리 Recoil 이란?  (0) 2021.12.27
react animation?  (0) 2021.04.22
React Styled Component에 대해 알아보자!  (0) 2019.10.07
canvas 라이브러리 Fabric Demo  (0) 2019.09.20
CORS 란?!  (0) 2019.09.16

+ Recent posts