styled-components vs emotion 비교

React 프로젝트 시작에 앞서 많은 개발자들이 사용하고 있는 css-in-js 스타일링 방식인 styled-components 와 emotion 중에 선택해서 사용해보기 위해 글을 작성해 보았다.

 

emotion 공식문서 : https://emotion.sh/docs/introduction

styled-components 공식문서 : https://styled-components.com/docs

 

깃허브

styled-components

https://github.com/styled-components/styled-components

 

emotion

https://github.com/emotion-js/emotion

 

트렌드

https://npmtrends.com/@emotion/react-vs-@emotion/styled-vs-styled-components

전반적인 다운로드 횟수는 @emotion/react < styled-components < @emotion/styled 정도이다.

참고로, @emotion/styled 는 emotion을 styled-components 처럼 사용할 수 있게 해주는 라이브러리 이다.

 

 

제공하는 기능

Library Attaching
Props
Media
Queries
Global Styles Nested Selectors SSR Theming Support Composition
styled-components Yes Yes Yes Yes Yes Yes Yes
emotion Yes Yes Yes Yes Yes Yes Yes

https://github.com/jsjoeio/styled-components-vs-emotion

 

 

 

기본 문법상의 차이

styled-components

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);

 

위의 예제를 이용해서 일반화를 해보면 아래와 같다.

// 사용법
const 컴포넌트이름 = styled.태그이름`
	// css 작성
`;

 

@emotion/react

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

const divStyle = css`
  background-color: hotpink;
  font-size: 24px;
  border-radius: 4px;
  padding: 32px;
  text-align: center;
  &:hover {
    color: white;
  }
`

export default function App() {
  return <div css={divStyle}>Hover to change color.</div>
}

styled-components 와 비슷한 방식으로 사용할 수 있지만, 다른 점이 있다.

jsx 안에서 html 태그의 이름을 바로 알 수 있다는 점이다.

 

styled-components 같은 경우는 component를 생성할때 이름에 div, p, span 등을 써놓지 않으면 jsx 부분에서 이게 어떤 태그인지 바로 알 수 없다. 

 

만약 코드 길이가 길어지고 디버깅 시에 각 태그를 하나하나 찾아야 한다면 굉장히 번거로워 질 것이다.

 

@emotion/styled

import styled from '@emotion/styled'

const Button = styled.button`
  color: turquoise;
`

render(<Button>This my button component.</Button>)

만약 emotion 을 위와 같이 styled-components 와 동일한 문법으로 사용하고 싶다면 @emotion/styled 라이브러리를 설치하면 된다.

yarn add @emotion/react @emotion/styled