티스토리 뷰
CSS in JS
📍리액트에서 css 적용법
- 인라인 스타일
- css 파일 작성 후 className으로 적용
- CSS in JS
📍CSS in JS 란?
- 자바스크립트 코드로 CSS 코드를 작성하여 컴포넌트를 꾸미는 방식
- style을 적용할 때 조건문, 변수 등 다양한 로직을 이용할 수 있다.
styled-components
📍styled-components 란?
- 리액트에서 CSS-in-JS 방식으로 컴포넌트를 꾸밀수 있게 도와주는 패키지
📍styled-components 설치 및 사용
- VSCode 내 확장프로그램 설치

- yarn으로 styled-components 설치하기 (터미널)
yarn add styled-components
- 기본적인 사용 방법
- 꾸미고자 하는 컴포넌트를 SC의 방식대로 먼저 만들고, 그 안에 스타일 코드를 작성하는 방식
- 가장 핵심이 되는 코드는 const StBox = styled.div``; (백틱 사용하기)
- styled. 뒤에는 html의 태그
div => styled.div
span => styled.span
button => styled.button
// 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;
- 조건부 스타일링 구현
- props를 사용 : box들에게 prosp를 통해서 border color에 대한 정보를 전달

// 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;
더보기
더보기
1. styled-component를 생성
const StBox = styled.div``;
2. 그리고 생성한 styled-component를 부모 컴포넌트에서 사용. (부모컴포넌트는 App.js)
const App = () => {
return (
<div>
<StBox>빨간 박스</StBox>
<StBox>초록 박스</StBox>
<StBox>파랑 박스</StBox>
</div>
);
};
3. 그리고 이제 우리가 원하는 값,
즉 borderColor를 props로 자식컴포넌트(styled-components)를 StBox 에 전달
const App = () => {
return (
<div>
<StBox borderColor="red">빨간 박스</StBox>
<StBox borderColor="green">초록 박스</StBox>
<StBox borderColor="blue">파랑 박스</StBox>
</div>
);
};
4. 자식 컴포넌트에서 받기
- 백틱 안에서 자바스크립트 코드를 사용하기 위해 ${ }
- 비어있는 화살표 함수 열기 ${( )=>{ }}
- 함수의 인자에서 props를 받아오고, props안에는 부모 컴포넌트에서 보낸 borderColor를 return
${(props)⇒{ return props.borderColor }}
- Switch문과 map을 사용해서 리팩토링
// src/App.js
import React from "react";
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", "green", "blue"];
// 색을 넣으면, 이름을 반환해주는 함수를 만듭니다.
const getBoxName = (color) => {
switch (color) {
case "red":
return "빨간 박스";
case "green":
return "초록 박스";
case "blue":
return "파란 박스";
default:
return "검정 박스";
}
};
const App = () => {
return (
<StContainer>
{/* map을 이용해서 StBox를 반복하여 화면에 그립니다. */}
{boxList.map((box) => (
<StBox borderColor={box}>{getBoxName(box)}</StBox>
))}
</StContainer>
);
};
export default App;
GlobalStyles
📍GlobalStyles(전역 스타일링) 이란?
- styled components는 컴포넌트 내에서만 활용
- 공통적, 전역적(globally) 스타일을 지정한다.
📍GlobalStyles 적용
- 기존 컴포넌트 단위 스타일링 (공통 부분 : font, line-height)
더보기
더보기
import styled from "styled-components";
function TestPage(props) {
return (
<Wrapper>
<Title>{props.title}</Title>
<Contents>{props.contents}</Contents>
</Wrapper>
);
}
const Title = styled.h1`
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
font-size: 1.5rem;
margin: 0;
margin-bottom: 8px;
`;
const Contents = styled.p`
margin: 0;
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
font-size: 1rem;
`;
const Wrapper = styled.div`
border: 1px solid black;
border-radius: 8px;
padding: 20px;
margin: 16px auto;
max-width: 400px;
`;
export default TestPage;
- GlobalStyles 적용
더보기
더보기
[GlobalStyle.jsx]
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
body {
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
}
`;
export default GlobalStyle;
[BlogPost.jsx]
function BlogPost({ title, contents }) {
return (
<>
<p>{title}</p>
<p>{contents}</p>
</>
);
}
export default App;
[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;
css reset
📍css reset 이란?
- 크롬, 사파리, 인터넷 익스플로러, 파이어폭스 등
브라우저에서 기본적으로 제공하는 스타일을 초기화하는 것 - margin 이나 글자의 크기 등
더보기
더보기
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;
}
[index.html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./reset.css" />
</head>
<body>
<span>Default Style을 테스트 해 봅니다.</span>
<h1>이건 h1 태그에요</h1>
<p>이건 p 태그에요</p>
</body>
</html>
'Language > React' 카테고리의 다른 글
| [⚛️] useEffect, useRef (0) | 2025.01.30 |
|---|---|
| [⚛️] useState : 함수형 업데이트 (0) | 2025.01.30 |
| [⚛️] useState() 를 왜 쓸까? (0) | 2025.01.22 |
| [React 입문 Day 2] state, 렌더링, Virtual DOM 간단 정리 (0) | 2025.01.21 |
| [⚛️] 카운터 앱 만들어보기 (0) | 2025.01.21 |