npm i @emotion/styled @emotion/react
emotion을 사용할 때 create-react-app(cra)을 사용하여 react 프로젝트 생성 시 emotion을 사용하기 위해서는 맨 위 상단에 /** @jsxImportSource @emotion/react */
을 추가해주어야 함
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const color = 'white'
export default function EmotionExample() {
return (
<div
css={css`
padding: 32px;
background-color: hotpink;
font-size: 24px;
border-radius: 4px;
&:hover {
color: ${color};
}
`}
>
Hover to change color.
</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;
&:hover {
color: white;
}
`
export default function EmotionExample(){
return(
<>
<Button></Button>
</>
)
}
styled component처럼 사용할 수 있으며 객체로도 넘겨서 사용할 수 있다.
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
/>
)
<P>pppp</P>
<ArticleText>Article</ArticleText>
위 코드를 통해 확인할 수 있는 것 처럼 다른 P 태그 컴포넌트를 그대로 사용하여 확장으로 css를 써줌으로써 나중에 넣어준 css로 덮어씌워진걸 볼 수 있다.
p 컴포넌트 값을 그대로 가지고 있으면서 오버라이드하여 새로운 css style로 덮어서 보여줌.
emotion도 css를 변수로 만들어 전역적으로 쓸 수 있다.
const danger = css`
color: red;
`
const base = css`
background-color: yellow;
color: turquoise;
`
<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>
배열로 받아오게 되면 무조건 두번째의 인자값으로 오버라이드 되어 나타나게 된다.