1. 예제를 위한 CRA 설치
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript
2. React Router 설치
yarn add react-router-dom
yarn add @types/react-router-dom
3-1. 기본 예제 - Non exact
- exact 속성이 없는 경우, path depth를 기준으로 상속 관계를 가진다.
- 많은 depth를 가진 라우터부터 규칙을 지키며 작성해야 한다.
import { Route, Switch } from 'react-router-dom';
import { FirstPage } from './pages/FirstPage';
import { SecondPage } from './pages/SecondPage';
import { ThirdPage } from './pages/ThirdPage';
import React from 'react';
export const Routes = () => (
<Switch>
<Route path="/third">
<ThirdPage />
</Route>
<Route path="/second">
<SecondPage />
</Route>
<Route path="/">
<FirstPage />
</Route>
</Switch>
);
3-2. 기본 예제 - exact
export const Routes = () => (
<Switch>
<Route path="/" exact={true}>
<FirstPage />
</Route>
<Route path="/second" exact={true}>
<SecondPage />
</Route>
<Route path="/third" exact={true}>
<ThirdPage />
</Route>
</Switch>
);
4. 중첩된 라우팅
import React from 'react';
import { Link, Switch, Route, useRouteMatch, useParams } from 'react-router-dom';
function SubPage() {
let { anyIdNameYouLike } = useParams();
return (
<div>
<h1>{anyIdNameYouLike}</h1>
</div>
);
}
export const ThirdPage = () => {
let { path, url } = useRouteMatch();
return (
<div>
<h1>Third Page</h1>
<nav>
<ul>
<li>
<Link to={`${url}/3-1`}>Sub-page-1</Link>
</li>
<li>
<Link to={`${url}/3-2`}>Sub-page-2</Link>
</li>
<li>
<Link to={`${url}/3-3`}>Sub-page-3</Link>
</li>
</ul>
</nav>
<hr />
<Switch>
<Route exact={true} path={path}>
<h3>Please select a sub-page.</h3>
</Route>
<Route path={`${path}/:anyIdNameYouLike`}>
<SubPage />
</Route>
</Switch>
</div>
);
};
5. 404 Page
- Route로 지정 되지 않은 페이지는 404 페이지를 렌더링한다.
import { Route, Switch } from 'react-router-dom';
import { FirstPage } from './pages/FirstPage';
import { SecondPage } from './pages/SecondPage';
import { ThirdPage } from './pages/ThirdPage';
import React from 'react';
import { PageNotFound } from './pages/PageNotFound';
export const Routes = () => (
<Switch>
<Route path="/" exact={true}>
<FirstPage />
</Route>
<Route path="/second" exact={true}>
<SecondPage />
</Route>
<Route path="/third">
<ThirdPage />
</Route>
<Route path="*">
<PageNotFound />
</Route>
</Switch>
);
6. 이외에 정보 및 출처
medium_Artem Diashkin