npm i react-router react-router-dom
npm i -D @types/react-router @types/react-router-dom
BrowserRouter
html5의 history api를 사용하여 UI를 업데이트.
URL이 변화하며 서버에 요청을 보내지 않지만 history는 관리가 된다.
기본적으로 서버에서는 URL에 해당하는 자원을 가지고 있지 않다.
따라서 새로고침시에 경로를 찾지 못하므로 서버에 추가 setting이 필요하다.
개발 환경에서 사용시 webpack option에 새로고침 경로 문제를 해결하는 방법
devServer: {
historyApiFallback: true
}
모든 Route의 root URL 설정
<BrowserRouter basename="/calendar">
<Link to="/today"/> // renders /calendar/today
</BrowserRouter>
<Prompt />
실행 시 행동 custom 설정 가능.
<BrowserRouter
getUserConfirmation={(message, callback) => {
// this is the default behavior
const allowTransition = window.confirm(message);
callback(allowTransition);
}}
/>
<BrowserRouter forceRefresh={true} />
페이지 전환시에 ssr처럼 페이지 전체가 refresh된다.
HashRouter
#(hash)를 이용하여 routing하는 기법.
url에 불필요한 #이 붙는다.
history.state를 사용할 수 없다.
새로고침 문제가 없으나 권장되지 않는 Router.
MemoryRouter
브라우저가 아닌 테스트 환경이나 모바일에 적합한 router
StaticRouter
location이 변화되지 않는 router. ssr에 적합.
Link
클릭시 url 이동
<Link to="/about">About</Link>
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
<Link to={location => `${location.pathname}?sort=name`} /
<Link to={location => ({ ...location, pathname: "/courses" })} />
history stack에 새 url이 추가되는 것이 아니라 현 url을 새 url로 교체.
<Link to="/courses" replace />
NavLink
Link와 비슷히지만 해당 nav가 활성화될 경우 styling 가능.
<NavLink to="/about">About</NavLink>
page가 활성화될 경우 추가될 className 지정
<NavLink to="/faq" activeClassName="selected">
FAQs
</NavLink>
page가 활성화 될 경우 nav Styling
<NavLink
to="/faq"
activeStyle={{
fontWeight: "bold",
color: "red"
}}
>
FAQs
</NavLink>
Link가 active되는 추가 조건을 설정
<NavLink
to="/events/123"
isActive={(match, location) => {
if (!match) {
return false;
}
// only consider an event active if its event id is an odd number
const eventID = parseInt(match.params.eventID);
return !isNaN(eventID) && eventID % 2 === 1;
}}
>
Event 123
</NavLink>
Prompt
페이지를 떠나기전에 사용자에게 확인 메시지 표시
<Prompt
when={formIsHalfFilledOut}
message="Are you sure you want to leave?"
/>
boolean true일 경우 prompt 실행
func일 경우 return 값 true면 페이지 이동 허용 string일 경우 message표시
<Prompt
message={(location, action) => {
if (action === 'POP') {
console.log("Backing up...")
}
return location.pathname.startsWith("/app")
? true
: `Are you sure you want to go to ${location.pathname}?`
}}
/>
Redirect
새 주소로 이동하지만 현재의 history stack을 덮어 씀.
<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
<Redirect
to={{
pathname: "/login",
search: "?utm=your+face",
state: { referrer: currentLocation }
}}
/>
Route
url이 일치할 경우 rendering component 설정
<Route path="/user/:username" component={User} />
component에 routeprops 이외에 다른 props를 넘겨줘야할 때 사용하기 좋은 방법
<Route path="/user/:username" render={(props) => <Component {...props} data={data} />)} />
Switch
location에 첫번째로 match되는 route만 rendering