Styled-component

Seunghwa's Devlog·2021년 3월 3일
0

Styled-component란?

Javascript 파일 내에서 CSS를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리로 React 프레임워크를 주요 대상으로 한 라이브러리다.

  • 설치
yarn add styled-component
  • 기본문법
// styled-components 라이브러리에서 import 해온 styled라는 객체를 이용한다
// 아래와 같이 h1태그를 만들어 Title이라는 styled 컴포넌트를 만들 수 있다
import styled from 'styled-componets'

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);
  • 생긴모양
const 위에서 지정한 component 명 = styled.태그명 ``
  • 스타일 지정
    스타일을 지정하기 위해 위의 예시 처럼 tagged template literal 사용
styled.태그명 ``; 부분에 해당
  • Adapting based on props
    속성에 기반하여 적용
const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.width < 200 ? "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 width="100">Primary</Button>
  </div>
);
  • Styled component Props 속성 사용 "전"
<TagBox className={isHidden ? "hidden" : "visible"}> 
  
----- -----   -----   -----   -----   -----   -----   -----    
.hidden {
  visibility: hidden;
}
.visible {
  visibility: visible;
}
  • Styled component Props 속성 사용 "후"
<TagBox unVisibility={isHidden}>
----- -----   -----   -----   -----   -----   -----   -----    

visibility: ${(props) => (props.unVisibility ? "hidden" : "visible")};

→ 이렇게 useState로 관리되는 상태 값을 props로 넘겨줄 수 있다

  • Extending Styles
    스타일을 상속 받을 수 있다
// 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>
);

→ TomatoButton은 기존의 스타일링된 Button을 extend해서 사용할 수 있다.

  • Styling any component
    스타일링된 메소드는 클래스이름 속성을 DOM에 연결하는 자신 또는 구성요소 모두에서 완벽하게 적용된다
// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
  color: palevioletred;
  font-weight: bold;
`;

render(
  <div>
    <Link>Unstyled, boring Link</Link>
    <br />
    <StyledLink>Styled, exciting Link</StyledLink>
  </div>
);
profile
에러와 부딪히고 새로운 것을 배우며 성장해가는 과정을 기록합니다!

0개의 댓글