Router 관련 Component
## React Router 설치
$ yarn add react-router-dom
## BrowserRouter Component
Route를 사용할 Component 상위에 랩핑해준다.
사용 예제
import React from 'react'
import { BrowserRouter } from 'react-router-dom';
import App from '../shared/App';
const Root = () => (
<BrowserRouter>
<App/>
</BrowserRouter>
);
export default Root;
## Route Component
import { Route } from 'react-router-dom';
url 패턴에 맞는 Component를 맵핑해 준다.
사용 예제
<Route path="/user/:type" component={User}/>
<Route path="/product" component={Product}/>
콜론(:)으로 되어 있는 URL은 맵핑되어 있는 Component에서 props에 전달되는 match 객체에서 꺼내 쓸수 있다.
props로 전달되는 객체
- history : push와 replace를 통해 다른 경로로 이동하거나 앞뒤 페이지로 전환 가능
- location : 현재 경로에 대한 정보를 가지고 있음
- match : 매칭되어 있는 라우팅 정보가 들어있음.
위 route에서 /user/:type 의 type 값을 User Component에서 참조하기 위해선 다음과 같이 하면 된다.
<h1>Type is {match.params.type}</h1>
## Switch Component
import { Route, Switch } from 'react-router-dom';
Route를 여러개 설정을 할 때 제일 처음 매칭 되는 Route만 노출 한다.
사용 예제
<Switch>
<Route path="/user/:type" component={User}/>
<Route path="/user" component={User}/>
</Switch>
## Link Component
import { Link } from 'react-router-dom';
URL을 변경 시 <a> 태그를 이용하면 페이지가 전환 되므로 <Link> Component를 이용해야 한다.
<ul>
<li><Link to={`/user`}>User</Link></li>
<li><Link to={`/user/:type`}>User Type</Link></li>
<li><Link to={`/product`}>Product</Link></li>
</ul>
## NavLink Component
import { NavLink } from 'react-router-dom'
Link 에 추가 기능이 포함됨. 클릭시 활성화된 URL에 특정 CSS 설정이 가능 함.
const Menu = () => {
const activeStyle = {
color: 'green',
fontSize: '2rem'
};
return (
<div>
<ul>
<li><NavLink exact to={"/"} activeStyle={activeStyle}>Home</NavLink></li>
<li><NavLink exact to={"/user"} activeStyle={activeStyle}>User</NavLink></li>
<li><NavLink to={"/user/:type"} activeStyle={activeStyle}>User Type</NavLink></li>
<li><NavLink to="/product" activeStyle={activeStyle}>Product</NavLink></li>
</ul>
</div>
)
};
activeStype 말고 activeClass 로 class명을 지정해도 됨.