본문 바로가기
React/Styled Components

[styled-components] styled-components

by Rayched 2024. 6. 26.

1. styled-components란 무엇인가?

https://styled-components.com/docs/basics#motivation

 

styled-components: Basics

Get Started with styled-components basics.

styled-components.com

 

공식 문서에 따르면, styled-components는 React Component의

CSS Style 설정을 좀 더 편하게 하기 위해서 고안된 라이브러리라고 한다.

 

React 컴포넌트의 스타일을 css 파일을 통해서 설정하는 방식과

styled-components 사용해서 스타일을 지정하는 방식은 무슨 차이가 있을까?

 

아래 예제를 통해서 이 둘의 차이를 한 번 비교해 보자.

 

① css 파일을 통해서 style 설정

//A, B라고 적힌 정사각형 두개를 return하는 Exam Component

function Exam(){
    return (
        <div>
            <div className="A">A</div>
            <div className="B">B</div>
        </div>
    );
}

 

/*Exam Component style setting*/

.Container {
    border: 3px solid black;
    padding: 2px;
    width: 50px;
    height: 50px;
    margin: 5px;

    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;

    font-weight: bold;
    font-size: 20px;
    color: white;
}

#A {
    background-color: red;
}

#B {
    background-color: blue;
}

 

예제 실행 결과

위와 같이 'style.css' 파일을 통해 React Component의 style을 설정하고

이를 App.tsx 파일에서 import 해서 React App에 style을 적용하였다.

 

Web 개발을 처음 배우기 시작했을 때부터 사용해 왔던 style 설정 방법으로 나름대로 익숙해지긴 했지만

개인적으로 조금 불편하다고 느끼는 점이 없잖아 있다.

 

이번엔 styled-components를 활용해서 React 컴포넌트의 style을 설정해 보자.


② styled-components 활용해서 style 설정

 

//styled-components 활용해서
//Exam의 style을 설정

import styled from 'styled-components';

const Container = styled.div`
  border: 3px solid black;
  padding: 2px;
  width: 50px;
  height: 50px;
  margin: 5px;

  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;

  font-weight: bold;
  font-size: 20px;
  color: white;
  background-color: ${(props) => props.bgColor};
`;

function Exam() {
  return (
    <div>
      <Container bgColor="red">A</Container>
      <Container bgColor="blue">B</Container>
    </div>
  );
}

 

styled-components의 styled 객체를 import 하고, Container라는 styled-components를 생성하였다.

이후 해당 컴포넌트의 style code를 위와 같이 작성하고 Exam에서 Container 컴포넌트를 두 번 생성했다.

 

그리고 이전 예제에서 배경색 값 외에는 중복됐던 코드를 props를 활용해서 개선했는데

이를 통해서 단순 css 코드 외에도 JavaScript를 사용할 수 있다는 것을 파악할 수 있다.

 

(결과물은 크게 달라지지 않기 때문에, 실행 결과는 별도로 첨부하지 않는다.)

 


1. styled-components

① styled-components 설치

 

앞에서 다룬 styled-components는 어쨌거나 외부 라이브러리이기 때문에

아래 명령어를 입력하는 것으로 설치를 진행해줘야 한다.

npm i styled-components

 

styled-components 설치가 완료되면, 아래와 같이 styled-components를 import 해준다.

import styled from "styled-components";

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

export default App;

② styled-components 생성

 

const Exam = styled.div`
	CSS 코드
`;

 

 

위와 같은 형식으로 입력하는 것을 통해서 styled-components를 생성할 수 있고

단순 <div>만이 아니라 <h1>, <p>, <input> 등 다양한 HTML 요소를 지정할 수 있다.

마지막으로 CSS 코드는 HTML 태그 이름 뒤에 있는 ``(백틱) 내부에 작성한다.

 

그리고 이런 식으로 생성한 styled-components는 React Component를 호출할 때와 같은 형식을 사용한다.

import styled from "styled-components";

const Exam = styled.div`
    border: 3px solid black;
    width: 50px;
    height: 50px;
    background-color: green;
`;

function App(){
    return (
    	<div>
        	<Exam />
        </div>
    );
};

export default App;

 

Exam Component의 CSS style이 문제없이 적용된 것을 확인할 수 있다.


styled-components의 생성과 사용법을 알았으니, 위의 예제에서 다른 색상의 정사각형을 만들어보자.

Exam2라는 새로운 styled-components를 생성, 배경색만 다르게 하고 나머지 코드는 Exam1과 동일하게 설정.

이후 App 함수에서 Exam1과 Exam2 컴포넌트를 호출한다.

import styled from "styled-components";

const Exam1 = styled.div`
    width: 50px;
    height: 50px;
    border: 3px solid black;
    background-color: green;
`;

const Exam2 = styled.div`
    width: 50px;
    height: 50px;
    border: 3px solid black;
    background-color: yellow;
`;

function App(){
    return (
    	<div>
            <Exam1>1</Exam1>
            <Exam2>2</Exam2>
        </div>
    );
}

 

각기 다른 색상의 정사각형 두 개를 생성했지만, Exam1과 Exam2는 배경색 외에는 죄다 중복되는 코드이다.

물론 이런 식으로 배경색 외에는 큰 차이가 없는 컴포넌트를 중복해서 만들 필요는 없다.

 

'Exam'이라는 공통되는 컴포넌트를 하나 만들고

배경색(background-color)과 같은 개별적인 부분은 props를 통해서 설정하는 것이 가능하다.

아래 예제 코드를 통해서 확인해보자.


③ props 통해 styled-components의 중복 코드 줄이기

 

import styled from 'styled-components';

const Exam = styled.div`
  border: 3px solid black;
  width: 50px;
  height: 50px;
  background-color: ${(props) => props.bgColor};
  margin: 3px;
`;

function App() {
  return (
    <div>
      <Exam bgColor="green">1</Exam>
      <Exam bgColor="yellow">2</Exam>
    </div>
  );
}

export default App;

 

'bgColor'라는 props를 생성하고, 해당 prop에 색상 값을 각각 전달하였다. ("green", "yellow")

그리고 bgColor의 값을 받는 Callback을 'background-color'의 값으로 전달한다.

이후 예제를 실행해 보면 아래와 같이 각기 다른 색상 값이 background-color로 전달된 것을 확인할 수 있다.

배경색을 바꾸지는 않았기에 실행 결과는 이전 예제와 동일하다.

 

이하의 과정을 통해서 styled-components에는 단순 CSS 코드만이 아니라

일반 JavaScript 코드도 사용할 수 있다는 것을 확인할 수 있었다.