create-react-appでreact-router
環境設定
router
フォルダでプロジェクトを作成
$ cd ~/
$ create-react-app router
react-routerインストール
今回はwebサイト
$ cd ~/router $ npm install --save react-router-dom
src/App.js 編集
- 前ページ共通で表示するHeader,Footer
- トップページは/
- /hoge, /moge でアクセスできるようにする
src/App.js
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const style = { common : { margin: 0, padding: "20px", textAlign: "center", width: "100%", height: "60px", backgroundColor: "#000", color: "#EEE" }, main : { fontSize: "1rem", padding: "40px" } } ; const Header = () => (<header style={style.common}>Common Header</header>); const Footer = () => (<footer style={style.common}>Common Footer</footer>); const TopPage = () => (<h1>Top Page</h1>); const HogePage = () => (<h1>Hoge Page</h1>); const MogePage = () => (<h1>Moge Page</h1>); const NoMatch = () => (<h1>Not found!! </h1>); class App extends Component { render() { return ( <Router> <div> <Header /> <nav> <ul> <li><Link to={process.env.PUBLIC_URL + "/"}>top</Link></li> <li><Link to={process.env.PUBLIC_URL + "/hoge"}>hoge</Link></li> <li><Link to={process.env.PUBLIC_URL + "/moge"}>moge</Link></li> </ul> </nav> <div style={style.main}> <Route exact path={process.env.PUBLIC_URL + "/" } component={TopPage} /> <Route path={process.env.PUBLIC_URL + "/hoge"} component={HogePage} /> <Route path={process.env.PUBLIC_URL + "/moge"} component={MogePage} /> <Route component={NoMatch}/> </div> <Footer /> </div> </Router> ); } } export default App;
ここで
<Route exact path={process.env.PUBLIC_URL + "/" } component={TopPage} />
exact
はその後の/hoge
や/moge
にマッチしないようにつける。process.env.PUBLIC_URL
は 本番配置するベースのURLをpackage.jsonのhomepage
設定を反映させるため
起動&確認
$ npm start
localhost:3000
localhost:3000/moge
Not Found の設定
上のApp.jsを以下のように変更&追加
src/Appjs
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
const NoMatch = () => (<h1>Not found!! </h1>);
<Switch style={style.main}> <Route exact path={process.env.PUBLIC_URL + "/" } component={TopPage} /> <Route path={process.env.PUBLIC_URL + "/hoge"} component={HogePage} /> <Route path={process.env.PUBLIC_URL + "/moge"} component={MogePage} /> <Route component={NoMatch}/> </Switch>
ブラウザで確認