리액트에서
컴포넌트
를스타일링
할 때는 아래와 같이 다양한 방식을 사용할 수 있다.
- 일반 CSS: 컴포넌트를 스타일링하는 가장 기본적인 방법이다.
- Sass: 자주 사용되는
CSS 전처리기
중 하나로 확장된CSS 문법
을 사용하여CSS 코드
를 쉽게 작성하도록 해준다.- CSS Module:
스타일
을 작성할 때CSS 클래스
가 다른CSS 클래스
의 이름과 충돌하지 않도록 파일마다 고유한이름을 자동으로 생성해주는 옵션이다.- styled-components:
스타일
을 자바스크립트 파일에 내장시키는 방식으로스타일
을 작성함과 동시에 해당스타일
이 적용된 컴포넌트를 만들 수 있게 해준다.
프로젝트
는 일반 CSS
방식으로 만들어져 있다.CSS
를 작성할 때 가장 중요한 것은 CSS 클래스를 중복되지 않게 만드는 것이다.규칙
을 사용하는 방법과, CSS Selector
를 사용하는 방법이 있다.App.css
를 보면 클래스 이름이 컴포넌트 이름-클래스
(ex. App-header) 형태로 지어져 있다.컴포넌트
이름을 포함하면 다른 컴포넌트
에서 실수로 중복되는 클래스를 만드는 것을 방지할 수 있다.BEM 네이밍
이라는 방법이 있다.CSS
방법론 중 하나로, 이름을 지을 때 일종의 규칙을 준수하여 해당 클래스가 어디에서 어떤 용도로 사용되는지 명확하게 작성하는 방법이다.CSS 클래스
가 특정 클래스 내부에 있는 경우에만 스타일
을 적용할 수 있다.스타일
을 적용하고 싶다면 다음과 같이 작성하면 된다..App .logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
}
App.css
와 App.js
의 CSS 클래스
부분을 수정했다.//App.css
.App {
text-align: center;
}
/* App 안에 들어 있는 .logo */
.App .logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
}
/* .App안에 들어 있는 header
header 클래스가 아닌 header 태그 자체에
스타일을 적용하기 때문에 . 생략 */
.App header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
/* .App 안에 들어 있는 a 태그 */
.App a {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
//App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header>
<img src={logo} className="logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
html 요소
에는 컴포넌트의 이름으로 클래스 이름을 짓고(.App), 그 내부에는 소문자를 사용하거나(.logo), header
, a
와 같은 태그를 사용하여 클래스 이름이 불필요한 경우에는 생략이 가능하다.CSS 전처리기
로 복잡한 작업을 쉽게 하도록 도와주고, 스타일 코드
의 재활용성을 높일 뿐만 아니라 코드의 가독성을 높여준다..scss
와 .sass
를 지원한다.//.sass
$font-stack: Helvetica, sans-serif
$primary-color: #333
body
font: 100% $font-stack
color: $primary-color
//.scss
$font-stack: Helvetica, sans-serif
$primary-color: #333
body {
font: 100% $font-stack
color: $primary-color
}
.sass
확장자는 중괄호({})와 세미콜론(;)을 사용하지 않는다..scss
확장자는 기존 CSS
를 작성하는 방식과 비슷하여 .scss
문법을 많이 사용한다.node-sass
라는 라이브러리를 설치했다.Sass
를 CSS
로 변환해준다.$ yarn add node-sass
src/SassComponent.scss
파일에 다음과 같은 코드를 작성했다.//SassComponent.scss
// 변수 사용하기
$red: #fa5252;
$orange: #fd7e14;
$yellow: #fcc419;
$green: #40c057;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;
// 믹스인 만들기(재사용되는 스타일 블록을 함수처럼 사용 가능)
@mixin square($size) {
$calculated: 32px * $size;
width: $calculated;
height: $calculated;
}
.SassComponent {
display: flex;
.box { // 일반 CSS에서는 .SassComponent .box와 마찬가지
background: red;
cursor: pointer;
transition: all 0.3s ease-in;
&.red {
// .red 클래스가 .box와 함께 사용되었을 때
background: $red;
@include square(1);
}
&.orange {
background: $orange;
@include square(2);
}
&.yellow {
background: $yellow;
@include square(3);
}
&.green {
background: $green;
@include square(4);
}
&.blue {
background: $blue;
@include square(5);
}
&.indigo {
background: $indigo;
@include square(6);
}
&.violet {
background: $violet;
@include square(7);
}
&:hover {
// .box에 마우스 올렸을 때
background: black;
}
}
}
src/SassComponent.js
파일의 코드는 아래와 같다.//SassComponent.js
import React from "react";
import './SassComponent.scss';
const SassComponent = () => {
return (
<div className="SassComponent">
<div className="box red" />
<div className="box orange" />
<div className="box yellow" />
<div className="box green" />
<div className="box blue" />
<div className="box indigo" />
<div className="box violet" />
</div>
);
};
export default SassComponent;
Sass 변수
및 믹스인
은 다른 파일로 따로 분리하여 작성한 뒤 필요한 곳에서 쉽게 불러와 사용할 수 있다.src
디렉터리에 style
라는 디렉터리를 생성하고 utils.scss
파일을 생성하여 SassComponent.scss
에 작성했는 변수
와 믹스인
을 분리했다.scss
파일을 불러올 때는 아래와 같이 @import
구문을 사용한다.@import './style/utils';
라이브러리
를 쉽게 불러와서 사용할 수 있다는 점이다.yarn
을 통해 설치한 라이브러리
를 사용하는 기본적인 방법은 아래와 같이 상대 경로를 사용하여 node_modules 까지 들어가서 불러오는 것이다.@import '../node_modules/library/styles';
스타일
파일이 깊숙한 디렉터리에 위치할 경우 ../를 많이 사용해야 하기 때문에 ~
을 사용하여 접근한다.@import '~library/styles';
~
를 사용하면 자동으로 node_modules
에서 라이브러리 디렉터리를 탐지하여 스타일을 불러올 수 있다.yarn
명령어를 통해 설치했다.$ yarn add open-color include-media
utils.scss
파일에서 설치한 라이브러리
를 불러왔다.//style/utils.scss
@import '~include-media/dist/include-media';
@import '~open-color/open-color';
(...)
라이브러리
를 사용하기 위해 SassComponent.scss
에서 배경색을 open-color
에서 회색을 사용하고, 화면 가로 크기가 768px
미만이 되면 어두운 회색으로 바꿔보았다.//SassComponent.scss
.SassComponent {
display: flex;
background: $oc-gray-2;
@include media('<768px'){
background: $oc-gray-9;
}
(...)
}
HTML
에서 사용하는 CSS
문법하고 크게 틀리지 않아서 쉽게 이해했지만 라이브러리를 불러오고 경로 설정하는 부분이 조금 헷갈린다..😂 Sass 변수 및 믹스인은 분리해서 관리 하자.
그리고 node_modules 내부 라이브러리 경로 안에 있는 scss
파일은 어디에 위치하고 있는지 확인 잘하기.❗