Programming/React

[React] react-router 사용하기

AlbertKo 2018. 8. 15. 15:55

안녕하세요. AlbertKo입니다.

오늘은 React-Router 라는 React의 ThirdParty Library를 사용해보도록 하겠습니다.

react-router란?

react-router

React는 다른 UI Framework 들과 다르게 Library인건 다들 알고 계실겁니다.
그러다 보니 웹을 개발하기 위한 전체적인 구성보다는 React는 Declarative View부분만 담당해줍니다.

그래서 SPA 안에서 redirect 없는 routing을 위해 나온 것이 react-router입니다.

react-router는 facebook에서 만든 것은 아니지만, react를 쓰면서 routing을 해야한다면
대부분의 사람들이 react-router lib를 사용하지 않을까싶네요 :)


원래 해당 라이브러리는 Angular / Express 등을 사용해보신 분들은 알듯이 '정적 라우팅 (static routing)을 어느정도 따라왔었어요

하지만, V4 이후 부터는 dynamic routing을 채택했다고합니다.


배경을 읽어보면


솔직하게 V2에서 (미카엘과 라이언 -> 개발자분들)은 많은 좌절을 겪었다고합니다.

API가 제한적이고, React의 일부들(LifeCycle과 그 외에)를 다시 구현해야한다고 느꼈고,

React가 지향하는 것과는 거리가 멀다고 생각을 했다고합니다.


그 결과 지금의 react-router가 되었고 만족할거라고 합니다 ㅋㅋ


지금의 react-router에서 static과 dynamic의 차이는 앱 외부에서 작업을 하는 것이 아닌 앱이 렌더링 될 때 진행된다고 보시면됩니다.

자세한건 밑에서 살펴보시죠.

설치 및 사용법

react-router을 사용할 프로젝트 안에서 설치를 진행하주면 됩니다.


NPM은 'yarn add' 를 'npm i --save' 로 바꿔주시면 됩니다.


yarn add react-router react-router-dom @types/react-router @types/react-router/dom


바로 들어가도록 하겠습니다.


우선, 'BrowserRouter'를 import 해줍시다.


import * as React from 'react';
import './App.css';

import { BrowserRouter } from 'react-router-dom';


그 후, Componnent를 작성해 주실 때,


Router를 이용할 곳을 BrowerRouter로 감싸줍시다


import * as React from 'react';
import './App.css';

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

import Exroute from './components/exroute/exroute'; // MyComponnent

class App extends React.Component {
public render() {
return (
<Router>
<div className="App">

</div>
</Router>
);
}
}

export default App;


위와 같이 진행해주시면 됩니다.


이제 클릭시 해당 path로 이동하도록 nav를 추가해 주고,

해당 path시 Exroute를 Render 할 수 있도록 코드를 추가해보겠습니다.


import * as React from 'react';
import './App.css';

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

import Exroute from './components/exroute/exroute'; // MyComponnent

class App extends React.Component {
public render() {
return (
<Router>
<div className="App">
<nav>
<Link to="/hello">hello</Link>
</nav>
<div>
<Route path="/hello" component={Exroute} />
</div>
</div>
</Router>
);
}
}

export default App;



그러면 동작을 한 번 봐볼까요??


위에 nav가 있네요! 한 번 눌러봅시다.


지정해둔 path로 redirect없이 이동 후 밑에 제가 Routing 해둔 Component를 Render해줬네요!



자세하게 알아가기

Router

모든 Router Component의 로우레벨 Interface입니다.

Router는 단 하나의 자식만을 Render해줍니다.


Route

Route Component는 가장 중요한 Component입니다!!

위치에 맞게 UI를 Render하기에 가장 기본적으로 알아야합니다.

주요 Props

    • exact : Component에 지정된 path가 현재 location에 자식이면 정확히 일치하는 주소가 아니라도 Render가 되는데, 이 옵션이 true시 path prop과 url이 정확히 일치해야 렌더됩니다.
    • path : 어느 location에서 Render를 할지 위치를 정해주는 prop입니다.
    • component : 외부에 Component를 넣어주면 Render시 해당 Component가 렌더됩니다.
    • render : 따로 렌더할 DOM을 정의해두지 않고 해당 prop에 하드코딩해 넣으면 해당 값이 Render됩니다.
    • props : Component에 아래의 props들을 전달합니다.
      • match : url path 에 대한 내용이 있습니다.
      • history : url 이동과 관련된 내용이 있습니다. (same : window.history , 하지만 SPA에 맞게되있음)
      • location : url을 다룰 수 있도록 구성되있습니다. (same : window.location) : 쿼리 스트링

Link

특정 위치로의 redirect 없이 이동을 하기위해 필요한 Component입니다.

Render시 <a>태그로 Render 됩니다.

주요 Props

    • to<string> : 이동할 path
    • to<object> : to에 json 리터럴 형식으로 입력해서 좀 더 상세하게 다룰 수 있습니다.
    • others : a태그에 관련된 props Attribute를 넣어줄 수 있습니다.


다음에 react-router을 좀 더 자세하게 써보도록 하겠습니다ㅎㅎ