Motivation

Styled Component가 나오게 된 동기는 간단하다. 예를 들어 어떤 컴포넌트에 스타일을 입힐 때 css를 사용한다면, className을 정해줘야 하고 만약 같은 스타일의 버튼을 만든다고 했을 때 서로 색만 다르다면 각각 색을 입혀주는 className을 만들어서 스타일을 만들어줘야한다. css의 길이만 길어지게 되는 것이다.
이러한 문제를 효율적으로 해결하기 위해 scss, sass와 같은 스타일 시트도 있지만 Styled Component에 대해 알아보려고 한다.

Installation

Styled Component를 리액트 프로젝트에 설치하기 위해서는 다음과 같이 인스톨 명령어를 사용한다.

npm install --save styled-components

설치한 style-components를 사용하기 위해서는 다음과 같이 임포트를 해야한다.

import styled from 'styled-components';

Usage

변수명을 정하고 style.[스타일을 입힐 태그명]`{스타일 코드작성}`와 같이 작성하면 된다. 다음은 예제 코드이다.

import React from 'react';
import styled from 'styled-components';

const App = () => {
  return (
    <Title>Hello React</Title>
  )
}

const Title = styled.h1`
  margin: 10px;
  font-size: 20px;
  color: #ab93c9;
`

export default App;

위 코드를 실행한 화면은 다음과 같다.

예를 들어 h1에 스타일을 입히고 싶다면 위와 같이 Styled Component를 사용하면 된다. 만약 같은 스타일에 색깔만 다르게 하고싶으면 다음과 같이 작성하면 된다.

import React from 'react';
import styled from 'styled-components';

const App = () => {
  return (
    <>
      <Title react>Hello React</Title>
      <Title>Hello Styled Component</Title>
    </>
  )
}

const Title = styled.h1`
  margin: 10px;
  font-size: 20px;
  color: ${props => props.react ? "#ab93c9" : "#d698b9"};
`

export default App;

위 코드를 실행한 화면은 다음과 같다.