styled-component

믕듀·2022년 1월 31일
0

React

목록 보기
5/10

이번 프로젝트를 진행하며 style-components를 활용하여 css를 구성해보자는 이야기가 나왔다.
그렇다면 style-components는 무엇일까?
styled-componets 공식문서

styled-componentsCSScomponent에 사용 할 수 있게 한다
mappingstyleㅈ과 component로 부터 제거함으로 component를 low-level styling 으로 구성하여 쉽게 사용 할 수 있게 도와준다

Motivation

style-componetsReact 컴포넌트를 설계하는데 있어 CSS styling을 enhance하는데서 나왔다.
제공하는 기능은 다음과 같다.

  • Automatic critical CSS: 렌더링 과정에서 구성 요소를 추적하고 자동으로 스타일을 삽입해준다.
  • No class name bugs: style-components는 스타일에 대한 고유한 클래스 이름을 생성한다. 중복 혹은 철자 오류에 대해 걱정할 필요없다.
  • Easier deletion of CSS: 클래스 이름이 코드베이스의 어딘가에 사용되는지 여부를 style-components는 분명히 한다. 구성 요소가 사용되지 않고 삭제되면 해당 구성 요소의 모든 스타일도 함께 삭제된다.
  • Simple dynamic styling: 수십 개의 클래스를 수동으로 관리하지 않고도 props 혹은 전역을 기반으로 구성 요소의 스타일을 적용하는 것이 간단하고 직관적이다.
  • Painless maintenance: 구성 요소에 영향을 주는 스타일을 찾기 위해 다른 파일을 검색할 필요가 없어 코드베이스가 크더라도 유지 관리는 편리하다.
  • Automatic vendor prefixing: CSS를 표준으로 작성하고 나머지를 style-components가 처리하도록 한다.

Start

// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// Use Title and Wrapper like any other React component – except they're styled!
render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);

JavaScript 혹은 React.js를 공부하였다면, 다음과 같은 예시 코드를 통해 쉽게 작동 방식을 알 수 있었다.
위의 변수 선언(Title, Wrapper)은 styled의 section과 h1의 tag 속성을 지닌 객체 선언처럼 보이며,
아래의 render 과정에서 선언된 변수는 tag로 사용됨을 알 수 있다.

조건부 styling

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

render(
  <div>
    <Button>Normal</Button>
    <Button primary>Primary</Button>
  </div>
);

위의 코드를 통해 styled-component에서 CSS 조건부 스타일링을 선언식 안에서 적용 할 수 있다는 것을 확인 할 수 있다.

재사용성

// The Button from the last section without the interpolations
const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

위의 코드는 Button의 속성에서 반복적인 부분 중 일부의 Button에 대해 추가/변경 하고 싶을 때 사용되는 방식이다. styled() 생성자로 앞선 styled-component를 상속받을 수 있다.

더 많은 정보는 공식문서를 통해 확인 할 수 있다.
또한 Tagged Template Literal를 이해 한다면, 더욱 styled-component를 이해하는데 도움이 될 것이다.

profile
Front-End 개발자가 되는 꿈을 꾸는ing

0개의 댓글