アプリ作成

react-router-domでルーティング (Wheather-app実装 7)

アプリ作成

こんにちは。kaoruです。

今回はSPAでの画面遷移(ルーティング)をReactで実装します。

【前回】useStateからuseReducerへ書き換え (Wheather-app実装 6)

実装

公式ドキュメントをチェック

新しいモジュールを触る時はQiita記事をまず見ていました。

概要をサッと理解するにはいいですが、実装時には公式ドキュメントをちゃんと見ることが近道ですね。当たり前かもですけど。

今回は以下をチェック
https://reactrouter.com/web/guides/quick-start

インストール

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

今はuse-react-routerは使わなくていいみたいです。

React Hooksで実装

Commit

(追記部分のみ)

import {
	BrowserRouter as Router,
	Switch,
	Route,
	Link
 } from "react-router-dom"

const Nav = styled.nav`
	display:flex;
	justify-content:center;
	margin-bottom: 10px;
	& a {
		margin-right: 10px;
	}
`


<Router>
	<Nav>
		<Link to="/">Weather</Link>
		<Link to="/about">About</Link>
	</Nav>

	<Switch>
		<Route path="/" exact>
			<WeatherWeek 
				forecasts={state.forecasts}
				visibleWeek={state.visibleWeek}
				dispatch={dispatch}
			/>
		</Route>
		<Route path="/about" exact>
			<About />
		</Route>
	</Switch>
</Router>

解説

<Link>で<a>タグを作ります。

<Route>は<Link>で指定したpathを受けて、<Route>の中身を描画します。

 … exact指定するとpathは完全一致になります。

<Switch>を使わない場合、<Route>は上から順にpathの前検索で該当するRouteを全て表示します。

<Switch>を使う場合、該当pathのRouteを一つだけ表示します。

まとめ

  • react-router-domだけで実装できる
  • Link と RouteのコンビでSPA画面遷移が実現できる

注意点としては、デフォルトは前方一致なので完全一致はexactを使う必要があるとこですね。

では、また〜。

コメント