Styled Components (1)

박주엽·2020년 9월 6일
0

Styled-components

목록 보기
1/2

Styled Components란?

말 그대로 스타일을 가진 컴포넌트라는 뜻으로 기존의 css,scss와는 다르게 동적인 스타일링을 할 수 있고 클래스네임을 사용하지 않고 다른 클래스네임으로 변경해주기 때문에 서로 겹치는 경우가 발생하지 않고 좀 더 동적이 스타일링을 할 수 있다. 그 외 자세한 내용은 해당 공식 문서를 참고하면 좋을거 같다.

설치

npm install --save styled-components

사용법

  1. import styled from "styled-components"; => 사용하고자 하는 컴포넌트에 임포트 한다.

  2. const "컴포넌트명" = styled."HTML element"`` => 이러한 형태로 컴포넌트를 스타일링 하고 백틱 안에 기존 CSS 문법으로 사용하면 된다.

  3. props로 전달

import React, { Component, Fragment } from 'react';
import styled from 'styled-components';
    
class App extends Component {
  render() {
    return (
      <Fragment>
		<Button>Hello</Button>
		<Button danger>Hello</Button>
      </Fragment>
    )
  }
}

const Button = styled.button`
	border-radius: 50px;
    padding: 5px;
    min-width: 120px;
    color: white;
    font-weight: 600;
    -webkit-appearance: none;
    cursor: pointer;
    &:active,
    &:focus {
      outline: none;
    }
    background-color: ${props => (props.danger ? 'red' : 'purple')}
`;

export default App;

위와 같이 스타일컴포넌트에 props를 할당하여 스타일에 background-color에 적용한 모습을 볼 수 있다.

  1. Nesting 기능도 활용하여 사용한다면 모든 컴포넌트를 스타일드 컴포넌트화 시키지 않더라도 충분히 스타일링할 수 있습니다.
render(
  <>
    <Thing>Hello world!</Thing>
    <Thing>How ya doing?</Thing>
    <Thing className="something">The sun is shining...</Thing>
    <div>Pretty nice day today.</div>
    <Thing>Don't you think?</Thing>
    <div className="something-else">
      <Thing>Splendid.</Thing>
    </div>
  </>
)

const Thing = styled.div`
  color: blue;

  &:hover {
    color: red;
  }

  #id {
		div {
	    background: orange;
		}
  }

  .something-else & {
    border: 1px solid;
  }

0개의 댓글