안녕하세요? YB 김채은입니다~!
제가 3주차 과제를 할 때는 스타일 컴포넌트 방식밖에 몰랐고, 심지어 파일 분리도 제대로 하지 못했던 상태라 코드가 상당히 가독성이 떨어졌었는데요ㅜㅜ 코드 리뷰를 하면서 한서OB님의 코드를 보고... 정말 감탄했습니다.. 🤩
수많은 이유가 있었지만 "html 구조가 명확하게 보여서 가독성이 좋았다는 점"에 꽂혀서 공부해 보니, emotion css 방식을 사용하셨더라구요! 이 방법을 사용하면 html 태그에 하나하나 이름을 지어줄 필요 없이, props로 스타일을 제어할 수 있다는 사실...ㅎㅎ
(저는 3주차 때 변수 이름을 짓는 게 너무 힘들었어요.........)
그래서 4주차 때 바로. 사용해 보았는데요!! 도중에 발생했던 개인적인 트러블 슈팅을 간단하게 소개해 보려 합니다//
/** @jsxImportSource @emotion/react */
import { loginStyle } from "./Login.style";
const Login = () => {
return (
<main css={loginStyle}>
<input type="text" name="id" placeholder="아이디" />
<input type="text" name="password" placeholder="비밀번호" />
<button type="submit">로그인</button>
</main>
);
};
export default Login;
import { Theme } from "@emotion/react";
import { css } from "@emotion/react";
export const loginStyle = (theme: Theme) =>
css`
display: flex;
flex-direction: column;
& input {
width: 20rem;
height: 2.5rem;
background-color: ${theme.color.white};
border: solid 0.1px ${theme.color.lightgray};
}
& button {
width: 20rem;
height: 2.5rem;
background-color: ${theme.color.button1};
border-width: 0;
}
`;
1. theme 적용 방법
스타일 컴포넌트 방식에서는 Theme을 적용할 때, 다음과 같이 작성합니다:
${({ theme }) => theme.color.primaryText}
반면, emotion css에서는 조금 더 직관적으로 Theme을 사용할 수 있습니다.
(theme: Theme) 형태로 Theme 타입을 지정한 뒤,
background-color: ${theme.color.white}
이런 식으로 간단하게 사용할 수 있죠.
2. JSX pragma 전역 설정하기
emotion의 css props에 접근하기 위해서는 css가 적용될 tsx파일 상단에 /** @jsxImportSource @emotion/react */ 이렇게 생긴 JSX pragma를 써주어야 합니다.
하지만 모든 tsx 파일마다 이 한 줄을 반복해서 쓰기엔 너무 귀찮죠..ㅎㅎ
이것을 전역으로 설정하는 방법이 있습니다..!!! 몇 가지 파일만 확인하면 되는데요,
1. tsconfig.app.json 파일 (❌❌❌ tsconfig.json 파일 아님!!! ❌❌❌)
{
"compilerOptions": {
/* ... */
"jsxImportSource": "@emotion/react",
/* ... */
}
2. vite.config.ts 파일
export default defineConfig({
plugins: [
react({
jsxImportSource: '@emotion/react',
}),
/* ... */
],
/* ... */
});
3. tsconfig.json 파일
{
"files": [],
/* ... */
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@emotion/react"
}
}
이렇게 세팅해주면 JSX pragma를 모든 파일에 쓰지 않아도, emotion의 css props에 접근할 수 있답니다 🤗
그럼 안~녕~
'4주차' 카테고리의 다른 글
타입스크립트 - interface (0) | 2024.12.16 |
---|---|
TanStack Query 집중공격 (0) | 2024.12.12 |
[React] 왜 TypeScript?? 그리고 interface VS type (0) | 2024.11.15 |
왜 Axios를 사용하는가? Fetch와의 비교로 알아보는 장단점 (0) | 2024.11.15 |
[4주차] AXIOS 알아보기 (0) | 2024.11.14 |