개발/React
#[React] 컴포넌트 CSS 스타일링
ForrestPark
2025. 2. 10. 17:00
chapter 03 컴포넌트 css 스타일링
CSS 를 사용한 리액트 컴포넌트 스타일링 방법
컴포넌트 스타일링
- 리액트 컴포넌트는 어떤 시점에서 html 요소로 바뀌므로 컴포넌트의 스타일링 또한 CSS를 사용해야함.
- index.html 파일에 html 코드를 작성하고 script 태그안에 자바스크립트 코드를 작성하는 일반적인 웹 프런트 엔드 개발과 다르지 않음.
부트스트랩 사용
- css 는 부트스트랩과 같은 css 프레임워크를 사용할 때가 많음.
- http://getbootstrap.com
- css 경로
- js 경로
- npm install
npm install bootstrap@5.3.3
public/index.html
<!-- Bootstrap CSS-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
부트스트랩 컴포넌트 구현
- 부트 스트랩 구문 > Forms > Overview > html 코드 복사 > Bootstrap.tsx 에 복사
- https://getbootstrap.com/docs/5.3/forms/overview/
export default function Bootstrap() { return <form> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> }
- 이렇게 쓰면 전부다 빨간줄 에러가 나는데 그 이유는 자바 키워드인 class 와 for 가 혼란을 주기 때문.
- 리액트에서는 다음처럼 class 대신 className, for 대신 htmlFor 라는 속성명을 사용해야함.
export default function Bootstrap() {
return (
<form>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"/>
<div id="emailHelp" className="form-text">We'll never share your email with anyone else.</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">Password</label>
<input type="password" className="form-control" id="exampleInputPassword1" />
</div>
<div className="mb-3 form-check">
<input type="checkbox" className="form-check-input" id="exampleCheck1"/>
<label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>)
}
이렇게 하면 브라우저에 부트스트랩이 적용된 화면 보임.
웹팩과 CSS 파일 임포트
- 웹팩은 이미지와 css 자바스크립트 또는 타입 스크립트 코드가 혼합된 프로젝트를 서비스하기 좋게 만들어줌.
- 특히 웹팩은 타입스크립트 코드에서 import 문 형태로 CSS 파일을 태그 없이 이용할수 있게 해줌.
- 예를들어 import './index.css' 처럼 css 파일을 임포트 해서 웹팩이 같은 디렉터리의 index.css 포함하여 배포됨.
CSS 기본 구문
- CSS 도 언어라서 작성하는 방법에 규칙 이잇음.
- 선택자(Selector) 설정ㅇ하고 선택자 뒤에 중괄호 {}를 사용해 감싸줌.
예: p 태그에 css 설정하는 예p : { color: red; font-size: 14px; line-height: 20px; }
선택자란?
CSS 선택자는 CSS 규칙을 적용할 HTML 요소를 정의함.
전체 선택자
* {
box-sizing: border-box;
}
유형선택자
h1, h2 {
font-family : Roboto, 'times New Roman', sans-serif;
}
클래스 선택자
.wrapper {
background-color: blue ;
}
...
<div class='wrapper' />
@import 규칙으로 아이콘 사용하기
- 앳 규칙 (at rules) : 대신 .css 파일에서 다른 .css 파일을 사용하고자 할 때 적용함.
@import url('https://fonts.googleapis.com/icon?family=Material+Icons);
- 구글 머티리얼 아이콘 설정하기
src/index.css
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');
.material-icons {
font-family: 'Material Icons';
display : inline-block;
}
src/page/Icon.tsx
// src/pages/Icon.tsx
export default function Icon() {
return(
<div>
<h3>Icon</h3>
<span className="material-icons">home</span>
<span className="material-icons">check_circle_outline</span>
</div>
)
}
- icon, 홈 아이콘과 체크 아이콘 생성됨 fonts.google.com/icons 를 참고하여 여러 아이콘 을 만들수 있음.
src/page/Style.tsx
// src/pages/Style.tsx
export default function Style() {
return (
<div>
<h3> Style </h3>
<span className="material-icons" style ={{color:'blue'}}>
home
</span>
<span className="material-icons" style={{fontSize: '50px', color:'red'}}>
check_circle_outline
</span>
</div>
)
}
Node.js 패키지 방식으로 아이콘 사용하기
@import 방식의 문제는 다른사이트에 호스팅된 외부 css 파일을 가져오므로 네트워크 속도에 영향받을 수있음.
웹 안전 글꼴 fontsource
@import 규칙은 웹에 안전한 글꼴 web safe font 를 사용.
머터리얼 아이콘 설치
yarn add @fontsource/material-icons
src/components/Icons.tsx
// src/components/Icon.tsx
import type {FC, CSSProperties} from 'react'
export type IconProps ={
name : string
style?: CSSProperties
}
export const Icon : FC<IconProps> =({name, style}) => {
return <span className="material-icons" style={style}>{name}</span>
}
}
- 이런식으로 컴포넌트를 만들면 받을 변수를 type IconProps 에서 받고 FC(function componet)로 stype 을 만들어 return 할수 있다.
- 의 style 부분을 선택한 후 f12 를 눌러 정의로 이동 하면 style 속성의 정의가 보이고 확인 가능.