CSS 문법을 그대로 사용
결과물을 styling된 컴포넌트 형태로 만들어주는 오픈 소스 라이브러리
# npm을 사용하는 경우
npm install --save styled-components
# yarn을 사용하는 경우
yarn add styled-components
import React from "react";
import styled from "styled-components";
const Wrapper = styled.div`
padding: 1em;
background: grey;
`;
소스코드에 고정된 값
let number = 20
// 20이 literal
// 정수 리터럴 (Integer literal)
const myNumber = 10;
// 문자열 리터럴 (String literal)
const myStr = 'Hello';
// 배열 리터럴 (Array literal)
const myArray = [];
// 객체 리터럴 (Object literal)
const myObject = {};
자바스크립트에서 제공하는 문법
// Untagged template literal
// 단순한 문자열
`string text`
// 여러 줄(Multi-line)에 걸친 문자열
`string text line 1
string text line 2`
// 대체 가능한 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);
import React from "react";
import styled from "styled-components";
const Button = styled.button`
// 내부에 props 사용, 해당 component에 사용된 props
color: ${props => props.darl ? "white" : "dark"};
background: ${props => props.dark ? "black" : "white"};
border: 1px solid black;
`;
function Sample(props) {
return (
<div>
<Button>Normal</Button>
<Button dark>Dark</Button>
</div>
)
}
export default Sample;
import React from "react";
import styled from 'styled-components';
// Button Component
const Button = styled.button`
color: grey;
border: 2px solid palevioletred;
`;
// Button에 style이 추가된 RoundedButton Component
// html 태그가 빠지고 Button Component, 다른 Component style을 확장
const RoundedButton = styled(Button)`
border-radius: 16px;
`;
function Sample(props) {
return (
<div>
<Button>Normal</Button>
<RoundedButton>Rounded</RoundedButton>
</div>
)
}
export default Sample;
❕ 참고 링크
https://styled-components.com/docs