React styled-components

Angela_Hong·2023년 7월 20일

React

목록 보기
2/5
post-thumbnail

React styled-components

설치

npm i styled-components

사용

import styled from 'styled-components';
// 버튼 스타일 컴포넌트 만드는 방법
// 하나의 컴포넌트이므로 꼭 대문자로 작성
const StyledButton = styled.button`
	background-color: black;
`;

styled-components 장점

  1. CSS파일을 따로 만들지 않고 JS파일 내에서 작성이 가능하다

  2. 원래 App.css에다가 css를 설정했다면 App.js뿐만아니라 하위 Detail.js에도 영향을 가게 만든다
    styled-components를 사용하면 해당 파일 내에서만 스타일이 적용된다

  3. 페이지가 많아질 경우 js, css 파일들이 많아지게 되는데 styled-components를 쓰면 한 파일에 정리가 가능해서 파일의 양을 줄일 수 있다

  4. 페이지 로딩시간이 단축된다. styled-components는 자동으로 html파일에 별도로 스타일 태그에 주입이 된다. css파일이 별도로 필요가 없기때문에 로딩시간이 단축된다

  5. 비슷한 컴포넌트 구성일 경우 다른 부분을 props로 넘겨줘서 재사용이 가능하다

const YellowBtn = styled.button`
  background-color: ${ props => props.color };
  color: ${props => props.color === 'blue' ? 'white' : 'black'}
`
// ${props => props.color}는 외부 라이브러리 사용 방법
// 간단한 프로그래밍도 가능하다
<YellowBtn color="blue">버튼</YellowBtn>
	* App.module.css 라고 작명을 하게 되면 App.js에 종속이 되게 된다
  1. 새로운 button을 만들었을 때 기존 button 디자인이 마음에 들어서 복붙하고 싶을 경우에 간단하게 사용할 수 있다
let NewBtn = styled.button(YellowBtn)`` 
//이렇게 하면 기존 YellowBtn이 가지고 있던 스타일들이 NewBtn에 복사가 된다

styled-components 단점

  1. js파일이 매우 복잡해진다
  2. styled-components인지 그냥 컴포넌트인지가 헷갈릴 수 있다
  3. 중복 디자인의 경우 다른 파일에서 import할텐데 css파일이랑 다른점이 없다
  4. 협업 시 css 담당 숙련도가 차이가 날 경우 문제가 발생한다

0개의 댓글