처음 만난 리액트(React) : section 15. Styling - 4 styled-components

꿀돼질래·2022년 9월 20일
0
post-thumbnail

💡 styled-components

styled-components

CSS 문법을 그대로 사용

결과물을 styling된 컴포넌트 형태로 만들어주는 오픈 소스 라이브러리

styled-components 설치하기

# npm을 사용하는 경우
npm install --save styled-components

# yarn을 사용하는 경우
yarn add styled-components

styled-components 기본 사용법

styled- components 사용 예시

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

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

tagged template literal 구성요소 스타일 지정

literal

소스코드에 고정된 값

다양한 종류의 literal

let number = 20
// 20이 literal


// 정수 리터럴 (Integer literal)
const myNumber = 10;

// 문자열 리터럴 (String literal)
const myStr = 'Hello';

// 배열 리터럴 (Array literal)
const myArray = [];

// 객체 리터럴 (Object literal)
const myObject = {};

template literal

자바스크립트에서 제공하는 문법

Untagged template literal과 Tagged template literal

// 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`;

Tagged template literal 사용한 예시

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의 props 사용하기

styled-components의 props 사용한 예시

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;

styled-components의 스타일 확장하기

styled-components 스타일 확장한 예시

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


🧠 마무리 하며...

매번 CSS를 사용할 때만 두루뭉술하게 썼는데 이번 강의를 통해서 구체적인 의미를 알 수 있어서 좋았다 나중에 참고하여 프로젝트에서도 써봐야겠다

0개의 댓글