@emotion/css
와 @emotion/react
가 있다. emotion/css는 react에 구애받지 않는 좀 더 심플한 버전이고, emotion/react는 css prop을 지원하고 SSR시 아무런 설정이 필요치 않은, react에 최적화된 버전이다.
@emotion/styled
패키지를 설치하면 컴포넌트 작성시 styled.div와 같은 style API
를 사용할 수 있다. 여기서는 @emotion/react와 @emotion/styled를 사용한 emotion 작성법을 알아보도록 하겠다.
emotion으로 스타일링하는 주요한 방법으로 css prop
이 있다. css prop은 컴포넌트를 스타일링하기 위한 간결하고 유연한 API를 제공한다.
css prop을 사용하는 방법으로는 Babel Preset
, JSX Pragma
두 방식이 있다.
이 방식은 CRA와 같이 bable custom configurations이 허용되지 않은 프로젝트에서는 사용할 수 없다.
리액트 16.14 이상에서 지원하는 new JSX runtime과 호환되고, next.js를 사용하는 환경이라면 .babelrc를 다음과 같이 설정한다.
babel custom configuration이 불가능한 환경에서는 JSX Pragma를 사용해야만 한다. 소스파일 최상단에 /** @jsx jsx */
를 기재하여 적용할 수 있다.
objects styles에 적용되는 css prop은 추가적인 import가 불필요하다.
string style에는 css를 import해서 써야한다. css prop을 tagged template literal같이 사용할 수 있다.
className??
emotion styled
는 styled-componets
로부터 많은 영향을 받았다.
styled 문법 내부의 props를 이용해서 컴포넌트의 스타일을 조절할 수 있다.
composition 기능을 사용하면 CSS의 계단식으로 적용되는(cascading) 우선순위에 구애받지 않을 수 있다.
import { css, jsx } from '@emotion/react'
const danger = css`
color: red;
`
const base = css`
background-color: darkgreen;
color: turquoise;
`
// {[danger, base]}는 danger의 속성이 적용되면서도
// base 속성이 우선시된다.
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>
)
<Global>
컴포넌트에 styles
prop을 적용해서 전역 CSS 스타일을 정의할 수 있다.
render(
<div>
<Global
styles={css`
.some-class {
color: hotpink !important;
}
`}
/>
<Global
styles={{
'.some-class': {
fontSize: 50,
textAlign: 'center'
}
}}
/>
<div className="some-class">This is hotpink now!</div>
</div>
)