css-in-js 형식으로 스타일을 사용할 수 있다.
className이 자동으로 부여되기 때문에 스타일이 겹칠 염려가 없다.
재사용이 가능하다.
props, 조건 등에 따라 스타일을 지정 가능하다.
vendor-prefixing, nested selectors, and media queries 등이 적용되어 작성이 간편하다.
styled component 사용방식과 css prop 기능을 지원하여 확장에 용이하다.
styled component보다 파일 사이즈가 작고, ssr시 서버 작업이 필요없다.
npm i @emotion/core @emotion/styled
@emotion/react @emotion/babel-preset-css-prop
// webpack.config.ts
.babelrc
{
"presets": ["@emotion/babel-preset-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>
)
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>
)
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>)
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>
)
import { jsx } from '@emotion/react'
render(
<div
css={{
color: 'darkorchid',
'& .name': {
color: 'orange'
}
}}
>
This is darkorchid.
<div className="name">This is orange</div>
</div>
)
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>
)
import { jsx } from '@emotion/react'
render(
<div
css={{
padding: 8,
zIndex: 200
}}
>
This has 8px of padding and a z-index of 200.
</div>
)
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>
)