TIL 30 day React 개념 두번째

Winney·2020년 10월 7일
0

React

목록 보기
2/4

Route와 sass를 배운 후기
처음 배울 때 sass는 크게 어렵지는 않지만 기존 CSS를 바꾸는 과정에서 어려움을 느꼈다.
특히 우리 팀은 변수와 mixin 사용하는 것을 팀이 처음부터 정하지 않고 거의 막바지에 결정 했기 때문에 바꾸느라 너무 고생을 했다. 아마 처음부터 sass를 사용했으면 sass의 매력을 더 느꼈을 것같은데 프로젝트를 들어가면 본격적으로 sass를 즐기면서 쓸 수 있을 것같다.
Route는 개념 자체는 어렵지 않은데 다시 혼자서 작성해보세요라고 하면 버벅댈 것만 같았다. 하지만 SPA의 장점을 활용할 수 있는 라이브러리라는 점에서 좀 더 익숙해졌을 때 더 살펴보고 싶은 욕심은 있다.
이 둘을 배우면서 왜 react가 library라고 불리는지 이해 할 수 있어서 좋았다. 앞으로 framework와 library가 헷갈릴 때 react, route, sass를 떠올릴 것같다.

1. SPA란?

Single Page Application, 페이지가 한 개인 어플리케이션을 뜻한다. 즉 하나의 웹 사이트는 하나의 html 파일만을 갖는다.

2. Routing이란?

다른 경로(path)에 따라 다른 화면(view)을 보여주는 방법이다. Routing을 이용하면 한 개의 html 파일 안에서 여러개의 페이지를 보여줄 수 있다. 단, react 자체에는 rounting 기능이 포함되어 있지 않기 때문에 react가 library로 분류된다.

3. React Router란?

react에서 routing 기능을 사용하기 위해 가장 많이 사용되는 Third-party library이다.

1) react-router설치

CRA(Create React App)만으로는 routing을 사용할 수 없기 때문에 react-router를 설치해야한다.

npm install react-router-dom --save

2) Route Component 구현

import React from 'react';
improt {
  BrowserRouter as Router,
  Switch,
  Route,
 } from 'react-router-dom'; // react-router 사용하기 위해 작성

 import Login from '/pages/Login/Login'; // Routing을 하고 싶은 페이지들 넣기 위해 작성
 import Main from '/pages/Main/Main';

 class Routes extends React.Component {
   render() {
     return (
       <Router> // Routing 기능을 쓰겠다.
        <Switch> // 하위 route들이 바뀔 수 있도록 하겠다.
          <Route exact path="/" component={Login} /> // 사용하고 싶은 페이지들 입력
          <Route exact path="/main" component={Main} />
        </Switch>
       </Router>
     )
   }
 }

 export default Routes;

3) index.js

ReactDOM.render(<Routes />, document.getElementById('root'));

index.js에 Routing 기능이 추가도니 Routes component를 넣어준다.

4) Route 이동

Route를 이용한 이동 방법에는 두 가지가 있다.
(1) component를 사용하는 방법
(2) withRouterHOC로 구현하는 방법

import React from 'react';
import { Link } from 'react-router-dom';

class Login extends React.Component {
  render() {
    return (
      <div>
        <Link to='/main'>메인페이지</Link>
      </div>
    )
  }
}

export default Login;

react-router-dom에서 제공하는 Link component는 DOM에서 로 변환한다.
JSX -> Babel -> JavaScript
cf.

(2) withRouterHOC 사용

import React from 'react';
import { withRouter } from 'react-router-dom';

class Login extends React.Component {

  goToMain = () => {
    this.props.history.push('/signup');
  }

  render() {
    return (
      <div>
        <button
          className="loginBtn"
          onClick={this.goToMain}
        >
          로그인
        </button>
      </div>
    )
  }
}

export default withRouter(Login);
  • onClick 이벤트를 통해 페이지 이동을 한다.
  • goToMain이라는 event handler에서 구현한 것처럼 props 객체의 history(this.props.history)에 접근해서 이동 할 수 있다.
  • 받은 history의 push 메서드의 인자로 Routes.js에서 설정한 path를 넘겨주면 해당 라우트로 이동 할 수 있다.
  • Login component에서 props에 route정보인 history를 받으려면 export하는 component에 withRouter로 감싸야한다.
  • withRouter와 같이 해당 component를 감싸주는 것을 HOC(High Order Component)라 한다.
  • 클릭 시 조건 없이 이동할 때 사용
    예) 상품 리스트에서 클릭시 상세페이지 이동
  1. withRouterHOC
  • 클릭 시 추가 로직이 필요할 때 사용
    예) 유료 서비스 기능 클릭 시 : 유료 서비스 가입했는지 확인 해야함
    예) 로그인 버튼 클릭 시: 기존 회원인지 확인 해야함
    • Backend API로 data(User Info) 전송
    • User Data 인증/인가
    • response message
    • case 나뉨
      : 회원 가입 되어있는 사람 -> Main page로 이동
      : 회원 가입 안 되어있는 사람 => Signup page로 이동

추가 로직 예시

  goToMain = () => {
   if(response.message === "valid user"){
     this.props.history.push('/main');
   } else {
     alert("회원가입 해주세요.")
     this.props.history.push('/signup');
   }
 }

4. Sass란?

Syntactically Awesome Style Sheets의 줄임말이다. CSS의 확장이다. CSS 구문과 완전 호환이 되지만 CSS를 더 효율적이고 쉽게 편집할 수 있다. CSS 기능과 함께 CSS 변수 및 nesting과 같은 추가 기능이 있다. 확장자는 .sass와 .scss이다. 일반적으로 .scss를 더 많이 쓴다.

1) 설치

npm install node-sass --save

node-modules 폴더에 node-sass 폴더가 생성되면서 package.json에 이름과 버전 정보가 기록된다.

2) 확장자

.sass와 .scss이다.

3) 특징

sass에는 다양한 기능이 있지만 기본적인 기능으로 nesting과 변수사용, mixin이 있다.

(1) Nesting

  1. CSS
nav ul {
  margin: 0;
  padding: 0;
  background-color: #dbdbdb;
  list-style: none;
}

nav li {
  display: inline-block;
}

nav a {
  display: block;
  padding: 4px 8px;
  text-decoration: none;
}
  1. nesting 사용 시
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
    li{
      display: inline-block;
    }
  }

  a{
    display: block;
    padding; 4px 8px;
    text-decoration: none;
  }
}

(2) 변수 활용, & 연산자, mixin

  1. CSS
login-container {
	display: flex;
	justify-content: center;
  align-items: center
}

button {
  width: 200px;
	height: 100px;
	background-color: blue;
}

button:hover {
	background-color: red;
	cursor: pointer;
}

input {
	background-color: blue;
}

input:focus {
  background-color: red;
}
  1. 변수 및 mixin 사용 시
$theme-color: blue;

@mixin flex-center {
	display: flex;
	justify-content: center;
  align-items: center
}

login-container {
  @include flex-center;
	button {
	  width: 200px;
		height: 100px;
		background-color: $theme-color;
		&:hover {
			background-color: red;
			cursor: pointer;
		}
	}
	input {
		background-color: $theme-color;
		&:focus {
		  background-color: red;
		}
	}
}
profile
프론트엔드 엔지니어

0개의 댓글