벨로퍼트 리액트 - 2-1 Sass
Sass의 정의
SASS : Syntactically Awesome Style Sheets. CSS 전처리기(Pre-processor). 복잡한 작업을 쉽게 할수 있게 해주고 코드의 재활용성을 높여주며 가독성을 높여 유지보수를 쉽게해준다.
Sass에서는 .scss와 .sass를 지원하는데 보통 scss가 더 많이 사용된다.
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 시작하기
- 리액트 프로젝트 생성 npx create-react-app styling-with-sass
- node-sass 라이브러리 설치 (Sass를 CSS로 변환해주는 역할)
$ cd styling-with-sass
$ npm add node-css
Sass 사용법
$blue: #228be6; // 변수 선언
동적으로 클래스 붙이기
className={['Button', size].join(' ')}
// 또는
className={`Button ${size}`}
⇒ 또는 classnames 라이브러리 이용
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
classNames(['foo', 'bar']); // => 'foo bar'
// 동시에 여러개의 타입으로 받아올 수 도 있습니다.
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// false, null, 0, undefined 는 무시됩니다.
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
.Button {
&.large {
}
}
// 위는 아래와 같음
.Button.large {}
& + & // class + class
&:hover // = class:hover
&:active // = class:active
Mixin
반복되는 코드는 mixin을 사용하여 재사용할수있다
@mixin button-color($color) {
background: $color;
&:hover {
background: lighten($color, 10%); // 색상 10% 밝게
}
&:active {
background: darken($color, 10%); // 색상 10% 어둡게
}
}
...
&.blue {
@include button-color($blue);
}
&.gray {
@include button-color($gray);
}
&.pink {
@include button-color($pink);
}
<button className={classNames('Button', size, color, { outline })}>
// {} 안에 들어있는 값은 true 일때만 적용된다
spread 와 rest
배열과 객체, 함수의 파라미터, 인자를 다룰때 사용. 컴포넌트에서도 사용가능!
...reset : 지정한 props를 제외한 값을 rest라는 객체에 모아주고 설정해준다.
컴포넌트가 어떤 props를 받을지 확실하지는 않지만 그대로 다른 컴포넌트나 html 태그에 전달을 해줘야 할때 활용하면 좋다!