230619 Styled Components

나윤빈·2023년 6월 19일
1

TIL

목록 보기
4/55

📌 CSS-in-JS: 자바스크립트로 CSS 코드를 작성하는 방식

1) 명령어로 패키지 설치

yarn add styled-components

2) styled-components 사용하기


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;

📌 props를 통해서 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달 받아 조건부 스타일링을 하기

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

const StBox = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid

  // 함수가 여러 줄 일 때!
    ${(props) => {
      return props.borderColor;
    }};

    // 한 줄 일 때는 {} 생략하고 써주기!!
  background-color: ${(props) => props.backgroundColor};
  margin: 20px;
`;

function App() {
  return (
    <>
      <StBox borderColor="red" backgroundColor="yellow">
        빨간박스
      </StBox>
      <StBox borderColor="blue">파랑박스</StBox>
      <StBox borderColor="green">초록박스</StBox>
    </>
  );
}

export default App;

자바스크립트 map과 switch를 사용해서 리팩토링

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;

📌 GlobalStyle (전역 스타일링) : 프로젝트 전체를 아우르는 스타일이 필요할 때 globally 선언

import { createGlobalStyle } from "styled-components";

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

export default GlobalStyle;
import "./App.css";
import { styled } from "styled-components";
import TestPage from "./components/TestPage";
import GlobalStyle from "./components/GlobalStyle";

function App() {
  return (
    <>
      <GlobalStyle></GlobalStyle>
      <TestPage title="제목입니다" contents="내용입니다"></TestPage>
    </>
  );
}

export default App;

📌 CSS Reset: default style 제거하기

1) reset.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;
}

2) index.js에서 reset.css import 해주기

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./reset.css";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
profile
프론트엔드 개발자를 꿈꾸는

0개의 댓글