【React】 React でルーティングをするには
【React】 React でルーティングをするには
tags: node
react
はじめに
ルーティング以外の環境構築はこちらです。
react-router をインストール
npm install --save react-router-dom
react-routerのgithubはこちらです。
使ってみる
ルーティングをして、2つの方法でページ遷移してみます。
ルーティング
Routeコンポーネントを使い、path を指定します。
また、path に一致するときに表示するコンポーネント を component か render を使って指定します。
import React, { Component } from 'react'; import { HashRouter, Route, Switch } from 'react-router-dom'; import MyComponent from 'MyComponent'; export default const Routes = () => ( <HashRouter> <Switch> {/* componentで指定する */} <Route exact path="/path/to/example1" component={MyComponent} /> {/* renderで指定する */} <Route exact path="/path/to/example2" render={ props => ( <MyComponent {...props}> ) } /> </Switch> </HashRouter> );
render では、props を明示的に渡す必要があります。
今回は、上位からの props をそのまま引き継ぐため {...props}
としています。
これは、render の代わりに component で指定したときと同じ動作になります。
Linkコンポーネントでページを遷移する
react-router-dom にある Linkコンポーネントを使ってページ遷移をします。
Linkコンポーネントに to を指定するだけなので、簡単です。
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; export default class MyComponent extends Component { render() { return ( <Link to="/path/to/example2"> Link </Link> ); } }
Link をクリックすると、/path/to/example2
にページが遷移します。
historyオブジェクトでページを遷移する
Route コンポーネントから渡される react-router の historyオブジェクト を使ってページ遷移をします。
こちらのほうが、スタイルを自由にしやすいのでオススメです。
import React, { Component } from 'react'; export default class MyComponent extends Component { handleLink = () => { const { history, } = this.props; history.push('/path/to/example2'); } render() { return ( <button type="button" onClick={this.handleLink}> Link </button> ); } }
ボタンをクリックすると、/path/to/example2
にページが遷移します。
React Router の詳細な説明はこちらです。
ありがとうございました。