(TIL 17일차) React (7)

빡기·2020년 2월 13일
0

TIL(Today I Learned)

목록 보기
11/43

Sass(Syntactically Awesome Style Sheets)

  • CSS-pre-processor(전처리기)
  • 복잡한 작업을 쉽게 해주고, 코드의 재활용성 및 가독성을 높여 유지보수에 유리하게 해줌
  • 보통 언급되는 전처리기 3대장으로 Less, Sass(SCSS), Stylus 존재
  • 문법은 Sass가 Stylus와 비슷하고, SCSS는 Less와 비슷하며, Sass와 SCSS는 하나의 컴파일러로 모두 컴파일 가능
  • 2006년부터 시작하여 가장 오래된 CSS 확장 언어이며 그만큼 높은 성숙도와 많은 커뮤니티를 가지고 있고 기능도 훌륭

Scss vs Sass

  • 보통 Sass를 많이 사용하기에 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 사용법

  1. node-sass 라이브러리 설치
$ npx create-react-app styling-with-sass
$ yarn add node-sass
  • 이 라이브러리리는 Sass를 css로 변환해주는 역할
  1. Button 컴포넌트 만들기
import React from 'react';
import './Button.scss';

function Button({ children }) {
  return <button className="Button">{children}</button>;
}

export default Button;
  1. scss 적용하기
$blue: #228be6; // 주석 선언

.Button {
  display: inline-flex;
  color: white;
  font-weight: bold;
  outline: none;
  border-radius: 4px;
  border: none;
  cursor: pointer;

  height: 2.25rem;
  padding-left: 1rem;
  padding-right: 1rem;
  font-size: 1rem;

  background: $blue; // 주석 사용
  &:hover {
    background: lighten($blue, 10%); // 색상 10% 밝게
  }

  &:active {
    background: darken($blue, 10%); // 색상 10% 어둡게
  }
}

Scss 특징

& 연산자

.Button {
  &.large {

  }
}
// 아래와 동일
.Button.large{  // 띄어쓰기 없음 주의!!
}

반복되는 작업 mixin

 &.blue {
    background: $blue;
    &:hover {
      background: lighten($blue, 10%);
    }

    &:active {
      background: darken($blue, 10%);
    }
  }

  &.gray {
    background: $gray;
    &:hover {
      background: lighten($gray, 10%);
    }

    &:active {
      background: darken($gray, 10%);
    }
  }

  &.pink {
    background: $pink;
    &:hover {
      background: lighten($pink, 10%);
    }

    &:active {
      background: darken($pink, 10%);
    }
  }
  
  // 아래와 같은 의미
  
  @mixin button-color($color) {
  background: $color;
  &:hover {
    background: lighten($color, 10%);
  }
  &:active {
    background: darken($color, 10%);
  }
} // scss 파일 맨위에 선언

 &.blue {
    @include button-color($blue);
  }

  &.gray {
    @include button-color($gray);
  }

  &.pink {
    @include button-color($pink);
  }

CSS Module

  • 컴포넌트 스타일링 할 시 CSS 클래스 중첩되는 것을 방지

예시

//Box.module.css
.Box {
  background: black;
  color: white;
  padding: 2rem;
}
import React from "react";
import styles from "./Box.module.css";

function Box() { // styles로 불러와서 styles에 접근
  return <div className={styles.Box}>{styles.Box}</div>;
}

export default Box;
  • 리액트 컴포넌트 파일에서 해당 CSS파일 불러올 때 CSS 파일에 선언한 클래스 이름은 모두 고유
  • CSS 클래스 이름이 만들어지는 과정에서는 파일 경로, 파일 이름, 클래스 이름, 해쉬값 등이 사용 가능
  • 클래스 이름에 대해 고유한 값을 만들었기에 다른 곳에서 같은 클래스명 중복에 대해 걱정 X

CSS 클래스 네이밍 규칙(하기 싫으면 CSS MOdule 사용)

  1. 컴포넌트 이름은 유니크하게 작성
  2. 컴포넌트 최상단 클래스는 컴포넌트 이름과 일치와 일치
  3. 컴포넌트 내부 CSS 클래스는 CSS Selector 사용 (Ex: .MyForm .my-input)

CSS Module 실전 (라이브러리 필요 X)

시작하기 전 Tip

$ yarn add react-icons // 아이콘 라이브러리 
// Font Awesome, Ionicons, Material Design Icons 이쁜 아이콘

react-icons문서 참고!!

  1. CheckBox.module.css 작성
.checkbox {
  display: flex;
  align-items: center;
}

.checkbox label {
  cursor: pointer;
}

/* 실제 input 을 숨기기 위한 코드 */
.checkbox input {
  width: 0;
  height: 0;
  position: absolute;
  opacity: 0;
}

.checkbox span {
  font-size: 1.125rem;
  font-weight: bold;
}

.icon {
  display: flex;
  align-items: center;
  /* 아이콘의 크기는 폰트 사이즈로 조정 가능 */
  font-size: 2rem;
  margin-right: 0.25rem;
  color: #adb5bd;
}

.checked {
  color: #339af0;
}
  1. CSS Module 사용할 컴포넌트에 import
import React from 'react';
import { MdCheckBox, MdCheckBoxOutlineBlank } from 'react-icons/md';
import styles from './CheckBox.module.css';

function CheckBox({ children, checked, ...rest }) {
  return (
    <div className={styles.checkbox}>
      <label>
        <input type="checkbox" checked={checked} {...rest} />
        <div className={styles.icon}>
          {checked ? (
            <MdCheckBox className={styles.checked} />
          ) : (
            <MdCheckBoxOutlineBlank />
          )}
        </div>
      </label>
      <span>{children}</span>
    </div>
  );
}

export default CheckBox;

⭐styled-components⭐

  • JS 안에 CSS 작성가능하게 해주는 최고의 라이브러리❗
  • 대안으로 emotion과 styled-jsx

styled-components 사용법

  • 스타일을 가진 컴포넌트 생성 가능
npm i styled-components 
npm i polished // lighten(), darken() 색상변화 라이브러리
// 라이브러리 설치
// App.js
//설치 한뒤 컴포넌트 위에 import
import React from 'react';
import styled, { ThemeProvider } from 'styled-components';
import Button from './components/Button';

const AppBlock = styled.div`
  width: 512px;
  margin: 0 auto;
  margin-top: 4rem;
  border: 1px solid black;
  padding: 1rem;
`;

function App() {
  return (
    <ThemeProvider
      theme={{
        palette: {
          blue: '#228be6',
          gray: '#495057',
          pink: '#f06595'
        }
      }}
    >
      <AppBlock>
        <Button>BUTTON</Button>
      </AppBlock>
    </ThemeProvider>
  );
}

export default App;
  • ThemeProvide를 이용하여 styled-components 로 만든 컴포넌트에서 palette 를 조회하여 사용
  • ThemeProvider 로 설정한 값은 styled-components 에서 props.theme 로 조회
// button.js

import styled, {css} from 'styled-components';

  /* 색상 */
  ${({ theme, color }) => { //비구조화로 간략하게 정리
    const selected = theme.palette[color];
    return css`
      background: ${selected};
      &:hover {
        background: ${lighten(0.1, selected)};
      }
      &:active {
        background: ${darken(0.1, selected)};
      }
    `;
  }}

export default Button;
  • CSS 코드를 조건부로 보여주고 싶으면 CSS import하고 사용해야 함

profile
Front End. Dev

0개의 댓글