Styled-Components 의 개념과 장단점 활용 알아보기

FE_04이상민·2024년 8월 6일
0

React 스타일

목록 보기
2/3

Styled-Components의 개념과 장단점

Styled-Components의 개념

Styled-Components는 React와 함께 사용되는 CSS-in-JS 라이브러리로, JavaScript파일 내에서 스타일을 정의할 수 있습니다.

import styled from 'styled-components';

const BlueButton = styled.button`
	background-color: blue;
	color: white;
	padding: 10px;
	border-radius: 4px;
`;

function App() {
	return (
		<>
		 <BlueButton>파란색 버튼<BlueButton>
		</>
	);
}

Styled-Components의 장단점

스타일이 컴포넌트에 한정되어 있어서 전역 스타일에 충돌이 발생하지 않습니다.
CSS의 모든 기능을 사용할 수 있으며, SASS와 같은 CSS 전처리기의 기능도 지원합니다.

런타임에 스타일을 생성하므로, 성능에 약간의 영향을 줄 수 있습니다.
프로젝트 크기에 따라 번들 크기가 커질 수 있습니다.

CSS-in-JS 의 개념

CSS-in-JS의 개념

CSS-in-JS 스타일은 JavaScript의 객체 형태로 정의하고, 컴포넌트와 함께 스타일을 구성합니다.

CDD의 개념

CDD의 개념

UI를 개별 컴포넌트 단위로 개발하고 조합하여 전체 애플리케이션을 구성하는 방법

styled-Components 설치

npm install styled-components

간단 예제

import styled from 'styled-components';

const BlueButton = styled.button`
  background-color: blue;
  color: white;
  padding: 10px;
  border-radius: 4px;
  margin: 10px;
  width: 200px;
`;

function App() {
  return (
    <>
      <div>hello</div>
      <BlueButton>파란색 버튼</BlueButton>
    </>
  );
}

export default App;

생성한 컴포넌트를 재사용하는 방법

import styled from 'styled-components';

const BlueButton = styled.button`
  background-color: blue;
  color: white;
  padding: 10px;
  border-radius: 4px;
  margin: 10px;
  width: 200px;
`;

const BigBlueButton = styled(BlueButton)`
	width: 300px;
	height: 300px;
	padding: 15px;
`

function App() {
  return (
    <>
      <div>hello</div>
      <BlueButton>파란색 버튼</BlueButton>
      <BigBlueButton>큰 파란색 버튼</BigBlueButton>
    </>
  );
}

export default App;

클래스명을 지정하지 않아도 되는 이유

Styled-Components는 클래스명을 자동으로 생성하여 스타일을 적용하기 때문에
따로 클래스명을 지정하지 않아도 됩니다.

2개의 댓글

comment-user-thumbnail
2024년 8월 6일

엄청 깔끔하게 정리되어 있어서 보기 좋네요 ㅎㅎ

답글 달기
comment-user-thumbnail
2024년 8월 7일

요점만 딱딱 짚어주셔서 읽기 좋았습니다! 감사합니다!

답글 달기