Skip to content

Styled-Components in progress

React에서 사용되는 대표적인 CSS-in-JS 라이브러리

💡 CSS-in-JS

JavaScript 안에서 CSS를 작성하는 방식

Install

bash
# 설치
$ npm install styled-components

jsx
// 불러오기
import styled from "styled-components";

사용법

1. 컴포넌트 만들기

jsx
const 컴포넌트이름 = styled.태그종류`
  css속성1: 속성값;
  css속성2: 속성값;
`;
jsx
const BlueButton = styled.button`
  background-color: blue;
  color: white;
`;

2. 컴포넌트 재사용

jsx
const 컴포넌트이름 = styled(재사용할컴포넌트)`
  추가할 css속성1: 속성값;
  추가할 css속성2: 속성값;
`;
jsx
const LargeBlueButton = styled(BlueButton)`
  width: 300px;
  padding: 20px;
`;
jsx
const LargeTextBlueButton = styled(LargeBlueButton)`
  font-size: 24px;
  font-weight: 800;
`;

3. Props 사용하기

jsx
const 컴포넌트이름 = styled.태그종류`
  css속성: ${(props) => 함수코드};
`;
jsx
const PropsButton = styled.Button`
  background-color: ${(props) => props.backgroundColor || "white"};
`;
jsx
const PropsButton = styled.button`
  width: ${(props) => props.width || "auto"};
  font-size: ${(props) => props.fontSize || "auto"};
  font-weight: ${(props) => props.fontWeight || 400};
  background-color: ${(props) => props.backgroundColor || "white"};
  color: ${(props) => props.textColor || "black"};
  padding: ${(props) => props.padding || 0};
  border-radius: ${(props) => props.radius || 0};
  margin: ${(props) => props.margin || 0};
`;

4. 전역 스타일 설정하기

jsx
import { createGlobalStyle } from "styled-components";
jsx
const GlobalStyle = createGlobalStyle`
  전역css속성1: 속성값;
  전역css속성1: 속성값;
`;
jsx
// 최상위 컴포넌트에 가져다 쓰기
<GlobalStyle />
jsx
const GlobalStyle = createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`;

장단점

장점

  • CSS도 컴포넌트화 할 수 있다.
  • CSS와 JS의 상호작용이 쉽다.
  • Class 이름을 자동으로 지어준다.
  • SASS 문법으로 작성할 수 있다.

단점

  • CSS 대비 추가 학습이 필요하다.
  • Class 이름이 직관적이지 않다.
  • JavaScript의 크기가 커진다.