반응형
Emotion.js
Emotion.js는 JavaScript 안에서 스타일을 작성할 수 있게 해주는 CSS-in-JS 라이브러리 중 하나다.
Emotion.js의 특징
- CSS-in-JS 형식
- 컴포넌트로 만들어 재사용 가능
- className이 자동으로 부여되여 중복 방지 (Global namespace)
- JavaScript에서 쓰이는 상수, props, 함수 공유하여 스타일 지정 가능
- 상속에 의한 영향이 없도록 격리 (Isolation)
- 미사용 코드 처리 (Dead Code Elimination)
- Styled-component와 구조적으로 유사하지만 파일 사이즈는 더 작음
- 서버 사이드 렌더링이 필요 없음
Emotion.js 사용법
설치
# Framework Agnostic: 프레임워크를 사용하지 않는 경우
npm install @emotion/css
# React
npm install @emotion/react
불러오기
/** @jsxImportSource @emotion/react */
// 위는 주석으로 보이지만,
// babel이 React.createElement 대신
// jsx를 jsx라는 함수로 변환하게 한다.
import { jsx, css } from '@emotion/react'
기본 스타일링
Styled-component와 구조가 매우 유사하다. 아래에서 a 태그처럼 nested 구조도 지원한다.
const divStyle = css`
background-color: hotpink;
font-size: 24px;
border-radius: 4px;
padding: 32px;
text-align: center;
&:hover {
color: white;
}
a {
color: red;
}
`
export default function App() {
return (
<div css={divStyle}>
<a>DIV</a>
</div>
)}
아래는 Styled-component의 예시다. emotion.js는 이와 다르게 jsx에서 태그를 그대로 사용해서 가독성이 좋다는 장점이 있다.
// Styled-component 예시
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const Sample = () => {
return (
<Title>
h1 타이틀
</Title>
)
}
export default Sample
미디어쿼리
render(
<p
css={css`
font-size: 30px;
@media (min-width: 420px) {
font-size: 50px;
}
`}
>
Some text!
</p>
)
공식 문서
https://emotion.sh/docs/introduction
Emotion - Introduction
Emotion is a library designed for writing css styles with JavaScript. It provides powerful and predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. Both string and objec
emotion.sh
반응형
'웹_프론트엔드 > 로드맵 챌린지' 카테고리의 다른 글
CSS 프레임워크 - reactstrap (0) | 2022.02.28 |
---|---|
웹 컴포넌트란? HTML Template, Custom Elements, Shadow DOM (0) | 2022.02.25 |
Modern CSS - Styled JSX (0) | 2022.02.23 |
Modern CSS - CSS Modules (0) | 2022.02.22 |
Modern CSS - Styled Component (0) | 2022.02.18 |