STYLE SHEET/Sass

React에서 Sass 사용하는 방법

두비_ 2022. 6. 27. 20:41
반응형

리액트 설치 후 경로에서 node-sass 설치

$ yarn add node-sass

해당 라이브러리는 sass로 작성된 코드를 css로 변환해줍니다

src 폴더에 components 폴더 생성

Button.js 파일 생성

import React from "react";

function Button() {
  return <div></div>;
}
export default Button;

추가 임포트

import './Button.scss';

div 요소 button으로 바꾸기

return <button></button>

Button 내부에 children 추가하고 랜더링

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

className 설정

<button className="Button">{children}</button>;

components 폴더에 Button.scss 파일 생성

scss에서 변수를 선언할 때는 $를 사용합니다

$blue: #228be6;
.Button {
  display: inline-flex;
}

버튼 생성

.Button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  outline: none;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  height: 2.25rem;
  padding-left: 1rem;
  padding-right: 1rem;
  font-size: 1rem;
  background: $blue;
  &:hover {
    //lighten은 색상의 밝기를 지정할 수 있다 //현재값은 색상을 10% 밝게 해준것
    background: lighten($blue, 10%);
  }
  &:active {
    //darken은 색상의 밝기를 어둡게 지정한다 // 현재값은 색상을 10% 어둡게 해준것
    background: darken($blue, 10%);
  }
}

Button.js에서 className="Button"을 Button.scss에 .Button에 선언한걸 확인할 수 있습니다

컴포넌트를 app에서 사용합니다

import "./App.css";
import Button from "./components/Button";

function App() {
  return (
    <div className="App">
      <div className="buttons">
        <Button>Button</Button>
      </div>
    </div>
  );
}

export default App;

버튼이 생성되었습니다

App.js에 App.scss import

import "./App.scss";

버튼에 추가효과 지정합니다

src 폴더에 App.scss를 생성하고 작성합니다

.App {
  width: 512px;
  margin: 0 auto;
  margin-top: 4rem;
  border: 1px solid black;
  padding: 1rem;
}