[React] 05. React Router

주히 🌼·2020년 9월 11일
0

React

목록 보기
5/8

🎈 SPA 란?

Single page Application -페이지가 한 개인 애플리케이션

원래는 각각의 페이지 수 만큼의 .html 파일이 존재했다.
그런데 리액트 프로젝트에서 .html 파일의 수는 단 🌟1개🌟 이다.

❔ 어떻게 그것이 가능할까?
Routing 을 사용하면 된다.

🎈 Routing이란?

Routing 이란 다른 경로(주소)에 따라 다른 View(화면)을 보여주는 것 이다.

리액트 자체에는 이러한 기능이 없기 때문에, 따로 설치해주어야 한다.
React-router 는 리액트의 라우팅 기능을 위해 가장 많이 사용 되는 라이브러리이다.

🎈 React Router

1. react-router 설치

설치를 원하는 디렉토리로 이동 후 터미널에서 아래와 같이 입력하면 설치가 된다!
npm install react-router-dom --save

2. Routes 컴포넌트 구현

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from 'react-router-dom';

import Login from './pages/Login/Login';
import Main from './pages/Main/Main';

class Routes extends React.Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/main" component={Main} />
        </Switch>
      </Router>
    )
  }
}

export default Routes;

3. index.js 수정

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

원래 위와 같았다면 이제 <App /><Routes /> 로 고쳐줘야한다.
왜냐하면 routing을 설정한 컴포넌트를 설정해줘야 실행되기 때문이다.

4. Route 이동하기

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;

react-router-dom 에서 제공하는 <Link> 컴포넌트는 DOM에서 <a> 로 변환된다.

  • <a> - 외부 사이트로 이동하는 경우
  • <Link> - 프로젝트 내에서 페이지 전환하는 경우

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
          class="loginBtn"
          onClick={this.goToMain}

          로그인
        </button>
      </div>
    )
  }
}
export default withRouter(Login);

<Link> 를 사용하지 않고 onClick 이벤트를 통해 페이지를 이동하는 방법도 있다.
바로 props 객체의 history(this.props.history) 에 접근 해서 이동하는 방법이다.

  • <Link> - 클릭 시 바로 이동하는 로직 구현 시
    (ex: Nav Bar, Aside Menu)

  • withRouterHOC - 페이지 전환 시 추가로 처리해야 하는 로직이 있는 경우
    (ex: 로그인 버튼 클릭시 백엔드와 데이터를 주고 받은 후 회원 가입되어 있는 사용자는 Main 페이지로, 아니면 SingUp 페이지로 이동시킴)

profile
하면 된다! 프론트앤드 공부 중 입니당 🙆‍♀️

0개의 댓글