위코드 17일차

김상연·2021년 3월 3일
0

wecode

목록 보기
17/42

08:00 ~ 03:30 헬스장
10:00 위코드 도착

오늘은 어제에 이어서 내가 기존에 만들었던 코드들을 리액트로 변환시켰다.

SPA

Single Page Application - 페이지가 한 개인 어플리케이션

기존에는 페이지의 수만큼 html 파일이 존재했지만 리액트에서는 오직 public 폴더에 html 하나만 존재한다. 이 페이지 안에 여러 개의 페이지를 보여주는 방법은 Routing을 사용한다.

Routing

다른 경로(url 주소)에 따라 다른 View(화면)을 보여준다.

리액트 자체에는 이러한 기능이 내장되어 있지 않다. 고로 리액트는 라이브러리로 분류된다.

react-router 설치

일단 vscode에서 터미널을 켜서 아래의 명령어로 설치해야 한다.

npm install react-router-dom --save

Routes 컴포넌트 구현하기(예시)

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from 'react-router-dom';
// 위의 import 값들은 router에 필수로 작성

import Login from './pages/Login/Login';
import Signup from './pages/Signup/Signup';
import Main from './pages/Main/Main';
// 받아올 페이지들을 불러들인다.

class Routes extends React.Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={Login} />         
          <Route exact path="/signup" component={Signup}/>
          <Route exact path="/main" component={Main} />
        </Switch>
      </Router>
    )
  }
}
// path에 '/'는 만약 페이지 주소가 http://localhost:3000/일 경우 3000 뒤의
/를 뜻함 가장 먼저 나타나는 주소에 부여. 

export default Routes;

src폴더에 router.js 파일을 생성 후 위와 같이 작성.

index.js

index.js 폴더로 이동 후
ReactDOM.render(<Routes />, document.getElementById('root'));
render 안의 첫번째 인자는 보여지게 하므로 Routes.js를 rendering한다는 것이다.

Route 이동하기

<Link>컴포넌트를 사용하는 방법과 withRouterHOC로 구현하는 방법 두 가지가 있다.
차이점은 withRouterHOC는 조건을 걸고 구현 가능하다.(ex 인증 인가)

<Link>컴포넌트 사용방법

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

class Login extends React.Component {
  render() {
    return (
      <div>
        <Link to="/signup">회원가입</Link>
      </div>
    )
  }
}

export default Login;

<a>태그와 비슷하다고 생각하면 됨.

withRouterHOC로 구현방법

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

class Login extends React.Component {

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

  // 실제 활용 예시
  // goToMain = () => {
  //   if(response.message === "valid user"){
  //     this.props.history.push('/main');
  //   } else {
  //     alert("너 우리 회원 아님. 가입 먼저 해주세요")
  //     this.props.history.push('/signup');
  //   }
  // }

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

export default withRouter(Login);

실제 활용예시는 좀 더 공부 후 정리할 예정이다.

0개의 댓글