본문 바로가기
강의/스파르타코딩클럽

[리액트 숙련주차] 2-1~2 Styled Components

by gardenii 2023. 6. 29.

2-1 Styled Components (개요)

1. Css-in-JS 방식

- JS 코드 -> CSS 코드

- JS코드로 컴포넌트를 꾸미는 방식

- Styled Components 패키지 사용

2. 패키지란?

- 외부에서 가져와서 사용할 수 있는 라이브러리

- 3rd party

- vsCode extension -> "vscode-styled-components" 설치 -> 터미널에서 "yarn add styled-compone
nts" 하여 설치

3. Styled Components 사용

- 꾸미고자 하는 컴포넌트를 Styled Component 방식으로 만들고, 스타일 코드 작성하는 방식으로 사용

// src/App.js

import React from "react";
// styled-components에서 styled 라는 키워드를 import 합니다.
import styled from "styled-components";

// styled키워드를 사용해서 styled-components 방식대로 컴포넌트를 만듭니다. 
const StBox = styled.div`
	// 그리고 이 안에 스타일 코드를 작성합니다. 스타일 코드는 우리가 알고 있는 css와 동일합니다.
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin: 20px;
`;

const App = () => {
	// 그리고 우리가 만든 styled-components를 JSX에서 html 태그를 사용하듯이 사용합니다.
  return <StBox>박스</StBox>;
};

export default App;

- 즉 SC 방식으로 컴포넌트를 만들고, 스타일된 컴포넌트를 html 태그처럼 사용하는 방식

- 임포트 해주기 -> import styled from "styled-components"

- const [컴포넌트 이름] = styled.[html 태그] ` (css 코드) ` 

4. 조건부 스타일링

- css 작성 시, 클래스명 부여하지 않아도 if문, switch문, 삼항연사 등을 사용하여 JS코드를 작성하듯이 스타일 코드를 작성할 수 있음

- props로 값 전달받고 사용 가능

- props 사용 시 ${ ( props ) => { props.borderColor } } 형식으로 사용

- 백틱(``) 내부에 있기 때문에 ${ } 사용 필요  

// src/App.js

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

// 1. styled-components를 만들었습니다.
const StBox = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid ${(props) => props.borderColor}; // 4.부모 컴포넌트에서 보낸 props를 받아 사용합니다. 
  margin: 20px;
`;

const App = () => {
  return (
    <div>
			{/* 2. 그리고 위에서 만든 styled-components를 사용했습니다. */}
			{/* 3. 그리고 props를 통해 borderColor라는 값을 전달했습니다. */}
      <StBox borderColor="red">빨간 박스</StBox>
      <StBox borderColor="green">초록 박스</StBox>
      <StBox borderColor="blue">파랑 박스</StBox>
    </div>
  );
};

export default App;

5. Switch와 map으로 리팩토링

import "./App.css";
import styled from "styled-components";

const StContainer = styled.div`
  display: flex;
`;

const StBox = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid ${(props) => props.borderColor};
  margin: 20px;
`;

const boxList = ["red", "blue", "green", "black"];

const getBoxName = (color) => {
  switch (color) {
    case "red":
      return "빨간 박스";
    case "blue":
      return "파란 박스";
    case "green":
      return "초록 박스";
    default:
      return "검정박스";
  }
};

function App() {
  return (
    <StContainer>
      {boxList.map((box) => {
        return <StBox borderColor={box}>{getBoxName(box)}</StBox>;
      })}
    </StContainer>
  );
}

export default App;

2-2 Styled Components (전역 스타일링)

1. Global Styles

- 전역 스타일링 : 프로젝트 전체를 아우르는 스타일! globally

- styled-components는 해당 컴포넌트 내에서만 사용가능했음

- 별도의 컴포넌트 생성 후, const globalStyle = createGlobalStyle ` ~ ` 로 스타일 생성

- 적용하고싶은 컴포넌트들의 상위 컴포넌트에 넣어줌 (App 컴포넌트 등)

// GlobalSytle.jsx

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  body {
    font-family: "Helvetica", "Arial", sans-serif;
    line-height: 1.5;
  }
`;

export default GlobalStyle;
App.jsx

import GlobalStyle from "./GlobalStyle";
import BlogPost from "./BlogPost";

function App() {
	const title = '전역 스타일링 제목입니다.';
	const contents = '전역 스타일링 내용입니다.';
  return (
    <>
      <GlobalStyle />
      <BlogPost title={title} contents={contents} />
    </>
  );
}

export default App;

2. Sass(Syntactically awesome Style Sheets)

- CSS를 효율적으로 사용하기 위해 만들어진 언어

- 재사용성을 높이고, 가독성을 향상시켜주는 방법

- 변수 사용

$color: #4287f5;
$borderRadius: 10rem;

div {
	background: $color;
	border-radius: $borderRadius;
}

- 중첩 (Nesting)

label {
      padding: 3% 0px;
      width: 100%;
      cursor: pointer;
      color: $colorPoint;

      &:hover {
        color: white;
        background-color: $color;
      }
}

- 다른 css 파일 import

// colors
$color1: #ed5b46;
$color2: #f26671;
$color3: #f28585;
$color4: #feac97;

//style.scss
@import "common.scss";

.box {
	background-color: $color3;
}

3. CSS reset

- 브라우저는 기본적으로 default style을 제공함 - margin, 글자 크기 등

- 이는 브라우저마다 다를 수 있음 -> 초기화 필요 

- css 초기화 코드

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}