Dev/React

[React] Styled-Components 사용법

taeyeoxn 2025. 1. 3. 23:03

1. CSS-in-CSS vs CSS-in-JS

 
• CSS-in-CSS
CSS를 별도의 .css 파일에 작성하고, HTML이나 React 컴포넌트에서 className이나 id로 연결한다.
 
CSS-in-JS
JavaScript 코드 안에서 CSS를 작성한다. 대표적으로 Styled-Components, Emotion 등이 있다.
 

2. Styled-Components

 
Styled-Components는 CSS를 별도의 파일이 아니라, 컴포넌트 안에서 바로 작성한다. 그리고 특정 이름을 가진 컴포넌트를 생성해서 그 안에 스타일을 넣는다.
 
기존 HTML 파일

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./index.js"></script>
    <style>
      .Circle {
        width: 5rem;
        height: 5rem;
        background: black;
        border-radius: 50%;
      }
    </style>
  </head>
  <body>
    <div class="Circle"></div>
  </body>
</html>

 
Styled-Components의 작성 방법은 다음과 같다.

const 컴포넌트명 = styled.태그명`
... 스타일 넣기 ...
`

 
만들고자 하는 Component의 reder 함수 밖에서 작성하며, 스타일을 묶을 때는 `...`(백틱)으로 묶어준다.
 
Styled-Components로 수정한 파일

import styled from 'styled-components';

const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: black;
  border-radius: 50%;
`;

function App() {
  return <Circle />;
}

export default App;

 
 왜 Styled-Components를 사용하는 것이 좋을까?

  • CSS 중첩 방지 : 컴포넌트 내부에 스타일을 정의하기 때문에, 다른 컴포넌트와 스타일 이름이 충돌하지 않는다.
  • 코드 가독성 : 스타일과 컴포넌트를 한 곳에 모아 두기 때문에, 각각의 컴포넌트가 어떤 스타일을 가지고 있는지 한눈에 파악할 수 있다.
  • 동적 스타일링 가능 : Props를 사용해 동적으로 스타일을 변경할 수도 있다.

 

3. Styled-Components를 분리해서 사용하기
 

Styled-Component를 분리하는 이유는 프로젝트를 진행하다 보면 같은 내용의 style을 여러 곳에서 똑같이 사용하는 경우가 있기 때문이다.
 
Styled-Components를 분리하는 방법은 다음과 같다.
 
 export

import styled from 'styled-components';

export const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: black;
  border-radius: 50%;
`;

 
각각의 컴포넌트에 'export'를 붙여 다른 파일에서도 사용할 수 있도록 만들어준다.
 
import

import { Circle } from './Circle.style';

function App() {
  return <Circle />;
}

export default App;

 
import해서 사용할 때, 컴포넌트를 하나씩 가져오는 방식이 아니라, 별칭을 사용하는 방법도 있다.

import * as S from './Circle.style';

function App() {
  return <S.Circle />;
}

export default App;

 
컴포넌트의 갯수가 늘어나는 프로젝트에서는 별칭을 사용하면 많은 수의 컴포넌트를 모두 호출할 필요 없이 쉽게 사용할 수 있다.
 

4. Styled-Components에 Props 적용하기

import React, { useState } from "react";
import styled from "styled-components";

function Example() {
  const [email, setEmail] = useState("");

  return (
    <ExampleWrap active={email.length}>
      <Button>Hello</Button>
      <NewButton color="blue">Im new Button</NewButton>
    </ExampleWrap>
  );
}

const ExampleWrap = styled.div`
  background: ${({ active }) => {
    if (active) {
      return "white";
    }
    return "#eee";
  }};
  color: black;
`;

const Button = styled.button`
  width: 200px;
  padding: 30px;
`;

// Button 컴포넌트 상속
const NewButton = styled.Button`
  // NewButton 컴포넌트에 color라는 props가 있으면 그 값 사용, 없으면 'red' 사용
  color: ${props => props.color || "red"};
`;

export default Example;

 
위의 코드를 보면, email이라는 state 값에 따라 ExampleWrap에 prop으로 내려준 active라는 값이 true of false로 바뀌게 된다.
 
Styled-Components는 내부적으로 props를 받을 수 있고, 그 props에 따라 스타일을 변경할 수 있다.