웹개발/React

React - Style 적용하기

bergerac 2025. 5. 16. 09:11

1. 일반 CSS 파일

CSS 파일을 import 해올 수 있다.

  • 전역 스타일 적용 가능
  • 클래스명이 충돌할 수 있음
  • 유지보수 어려움
import './App.css';

function App() {
  return <div className="wrapper">Hello, CSS!</div>;
}

 

2. CSS 모듈

CSS 모듈은 파일명을 컴포넌트명.module.css 형식으로 작성하여 import 하는 방식이다. 클래스명이 자동으로 해싱되므로 전역 스타일 충돌 문제를 해결할 수 있다.

 

  • 컴포넌트 단위로 스타일 관리
  • 클래스명 충돌 방지
  • 전역 스타일링에는 부적합
import styles from './Index.module.css';

<div className={styles.wrapper}>
  Hello, I'm <span className={styles.text}>CSS Module</span>
</div>

 

 

3. styled-components

CSS-in-JS라이브러리 중 하나로서 JS 파일 안에서 직접 스타일을 작성할 수 있고, props기반 조건부 스타일링도 가능

 

  • 컴포넌트 기반 스타일링
  • props로 조건부 스타일링 가능
  • CSS 문법 그대로 사용 가능
  • ThemeProvider 제공
import styled from 'styled-components';

const MyButton = styled.button`
  background-color: black;
  color: pink;
  padding: 12px 24px;
  border-radius: 8px;

  &:hover {
    background-color: #45a049;
  }
`;

<MyButton>스타일드 컴포넌트 버튼</MyButton>

 

4. Emotion

Emotion은 또다른 CSS - in- JS라이브러리로 두가지 방식으로 스타일을 작성할 수 있다.

(1) css 함수 이용 (@emotion/react)

/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';

const boxStyle = css`
  width: 300px;
  height: 300px;
  background-color: orange;
`;

<div css={boxStyle}>Emotion Box</div>

 

  • /** @jsxImportSource @emotion/react */ 선언 필수
  • css props로 스타일을 직접 적용

(2) styled 함수 이용 (@emotion/styled)

import styled from '@emotion/styled';

const EmotionStyledButton = styled.button`
  background-color: hotpink;
  color: white;
  padding: 12px 24px;
`;

<EmotionStyledButton>이모션 버튼</EmotionStyledButton>
  • styled-components와 사용 방식 거의 동일
  • props 기반 조건부 스타일도 지원

로그인 페이지 스타일링하기

<div css={s.layout}>
  <div css={s.main}>
    <input ... />
    <input ... />
    <button>로그인</button>
  </div>
  <div css={s.footer}>
    <span>계정이 없으신가요?</span>
    <Link to={"/signup"}>회원가입</Link>
  </div>
</div>

 

export const layout = css`
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 100px;
`;

export const main = css`
  display: flex;
  flex-direction: column;
  border: 1px solid #dbdbdb;
  padding: 40px;
  width: 400px;
`;

'웹개발 > React' 카테고리의 다른 글

React - Zustand  (0) 2025.05.15
React - Context  (1) 2025.05.14
React - Axios로 HTTP 요청 보내기  (0) 2025.05.13
React - routing, navigate  (0) 2025.05.12
React - 커스텀 훅(Custom Hook)만들기  (0) 2025.05.11