# styled-components

- css를 그대로 사용하면서 스타일링 된 컴포넌트로 만들어 주는 오픈소스 라이브러리

설치

# npm을 사용하는 경우

npm install --save styled-components

예)

import React from "react";
import styled from "styled-components";

const Wrapper = styled.div`
    padding: 1em;
    background:grey;
`;

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

function MainPage(props){
    return ( 
        <Wrapper>
            <Title>
                안녕, 페라리!
            </Title>
        </Wrapper>
    )
}

export default MainPage;

# 기본 사용법

- tagged template literal : 구성요소의 스타일을 지정한다
- literal(고정된 값)

let number = 20; //--> 20이 literal을 의미한다

- template literal: 템플릿을 리터럴 형태로 사용하는 것

// Untagged template literal
// 단순한 문자열
`string text`

// 대체 가능한 expression이 들어있는 문자열
`string text ${expression} string text`

// Tagged template literal
// myFunction의 파라미터로 expression으로 구분된 문자열 배열과 expression이 순서대로 들어간 형태로 호출됨
myFunction `string text ${expression} string text`;


예제코드)

const name = '페라리';
const region = '이탈리아';

function myTagFunction(strings, nameExp, regionExp) {
  let str0 = strings[0]; // "제 이름은  "
  let str1 = strings[1]; // "이고, 사는 곳은 "
  let str2 = strings[2]; // "입니다."
 
  // 여기서도 template literal을 사용하여 리턴할 수 있음
  return `${str0}${nameExp}${str1}${regionExp}${str2}`;
}

const output = myTagFunction`제 이름은 ${name}이고, 사는 곳은 ${region}입니다.`;

// 출력 결과
// 제 이름은 페라리이고, 사는 곳은 이탈리아입니다.
console.log(output);  

템플릿 리터럴


styled-components 사용 예시

import React from "react";
import styled from "styled-components";

const Wrapper = styled.div`
	padding : 1em;
	background : grey;
`;

styled-components의 props 사용하기

import React from "react";
import styled from "styled-components";

const Button = styled.button`
	color: ${props => props.dark ? "white" : "dark"};
	background: ${props => props.dark ? "black" : "white"};
	border: 1px solid black;
`;

function Sample(props) {
  return (
    <div>
      <Button>Normal</Button>
      <Button dark>Dark</Button> // props로 dark를 전달해 주었다
    </div>
  )
}

export default Sample;

styled-components의 스타일 확장하기

import React from "react";
import styled from "styled-components";

const Button = styled.button`
	color: grey;
	border: 2px solid palevioletred;
`;

// Button에 style이 추가된 RoundedButton 컴포넌트
const RoundedButton = styled(Button)` // --> 확장해서 사용하는 부분
	border-radius:16px;
`;

function Sample(props) {
  return (
    <div>
      <Button>Normal</Button>
      <RoundedButton>Rounded</RoundedButton> 
    </div>
  )
}

export default Sample;

스타일드 컴포넌트

profile
페라리 타는 백엔드 개발자

0개의 댓글