React는 크게 2가지 방식으로 컴포넌트의 스타일을 적용한다.
- CSS in CSS
- 리액트 컴포넌트 별로 css 파일을 갖는 형식으로 스타일을 관리
- CSS Module
- 별도의 자바스크립트 전환 필요 없음(속도가 빠름)
- CSS in JS
- 자바스크립트 내에서 css를 작성하는 방식
- 대표적인 라이브러리로 styled-component, emotion 등이 있음
- 현재 사용중인 스타일만 DOM에 포함시킬 수 있음
- 별도 패키지를 설치하기 때운에 용량이 증가함(스크립트 전환이 필요하여 속도가 다소 느려짐)
🔥 CSS in JS 방식으로 하기위해 Emotion 적용하기
yarn add @emotion/react @emotion/styled
또는
npm install @emotion/react @emotion/styled
설치 완료되면 package.json에서 확인 가능하다.
App.jsx에 CSS-in-JS 방식 적용
import React from 'react';
import logo from './logo.svg';
import './App.css';
import styled from '@emotion/styled';
const Container = styled.div`
text-align: center;
`;
const Header = styled.header`
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
`;
const AppLogo = styled.img`
height: 40vmin;
pointer-events: none;
@media (prefers-reduced-motion: no-preference) {
{
animation: App-logo-spin infinite 20s linear;
}
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
`;
const AppLink = styled.a`
color: #61dafb;
`;
function App() {
return (
<Container>
<Header>
<AppLogo src={logo} alt={'logo'} />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<AppLink
href='https://reactjs.org'
target='_blank'
rel='noopener noreferrer'
>
Learn React
</AppLink>
</Header>
</Container>
);
}
export default App;