현업에서 styled-components 아니면 emotion을 많이 쓴다고 해서 emtion 쓰는 법을 정리 해보려고 합니다..
styled-components는 너무 많이 써봤기 때문에 emotion을 써보려합니당당구리
● css 모듈만 사용하기
npm create vite@latest
vite 프로젝트를 만든 후,
npm i @emotion/react
이모션을 설치해줍니다.
이후, tsconfig.json 파일에 아래 코드를 추가해 설정해줍니다.
"jsxImportSource": "@emotion/react",
그럼 끝 !!
import { css } from '@emotion/react'
export default function App() {
return (
<div
css={css`
padding: 32px;
background-color: hotpink;
font-size: 24px;
border-radius: 20px;
`}
>
Hover to change color.
</div>
)
}
위와 같은 코드로 css를 불러와 사용하면 됩니다. 그럼 아래와 같이 보이게 됩니닥닥 호호 신기
import { css } from '@emotion/react';
const style = css`
width: 200;
height: 300;
color: hotpink;
font-size: 20px;
background-color: blueviolet
`
export default function App() {
return (
<div css={style}>안녕하세요</div>
)
}
그리고 위와 같이 스타일을 변수화 해서 css에 넣을 수 있다.
● styled 모듈사용하기
그다음 나는 styled-components 처럼 styled를 쓰고싶쇼잉.. 아래 깔아잉
npm i @emotion/styled
import styled from '@emotion/styled';
const Button = styled.button`
color: turquoise;
`
export default function App() {
return (
<Button>This is my button.</Button>
)
}
그럼 위와 같이 내용이 나온다 ㅎ-ㅎ
● 나이제 props 쓰고시퍼잉
이제 props로 넘겨주고 싶은 값들이 생긴다면..?
import styled from '@emotion/styled';
// props의 타입을 지정해준다.
const Button = styled.button<{check: boolean}>`
padding: 30px;
background-color: ${(props) => props.check ? "blue" : "hotpink"};
color: white;
`
export default function App() {
return (
// props에 넘겨준다.
<Button check={false}>안녕 나는 버튼이다.</Button>
)
}
호버효과넣고싶으면 &:hover{ ~~ } 로 적어주면된다.
import styled from '@emotion/styled';
const Button = styled.button<{check: boolean}>`
padding: 30px;
background-color: ${(props) => props.check ? "blue" : "hotpink"};
color: white;
&:hover{
background-color: black;
}
`
export default function App() {
return (
<Button check={true}>안녕 나는 버튼이다.</Button>
)
}
Emotion(Styled), Props 전달하기(Typescript) - WORLD IS WIDE
컴포넌트 내부에서 사용하는 변수를 CSS에 전달하여 동적 스타일을 사용하기 위해서는 props를 전달하는 방법이 있습니다. Typescipt를 사용 시 발생하는 에러를 해결하기 위해 사용하는 타입 선언
choonse.com
Emotion – Introduction
(Edit code to see changes)
emotion.sh
Emotion – TypeScript
Emotion includes TypeScript definitions for @emotion/react and @emotion/styled. These definitions infer types for css properties with the object syntax, HTML/SVG tag names, and prop types. @emotion/react The easiest way to use the css prop with TypeScript
emotion.sh
됏어 나는 이모션 다룰줄안다•••!!!!!!!!!!!!!!!!