mo49
4/5/2020 - 6:59 AM

00_ReactRouter.md

Reactでルーティング

react-router-domの使い方

https://github.com/ReactTraining/react-router#readme

import React, {Component} from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from 'react-router-dom'
import Top from './Top'
import About from './About'
import Article from './Article'

class App extends Component {
  render(h) {
    const current = {color: 'Red'}
    return (
      <Router>
        <div className="App">
          <ul>
            <li><NavLink exact to="/" activeStyle={current}>Top</NavLink></li>
            <li><NavLink to="/about" activeStyle={current}>About</NavLink></li>
            <li><NavLink to="/article/1" activeStyle={current}>Article No.1</NavLink></li>
            <li><NavLink to="/article/2" activeStyle={current}>Article No.2</NavLink></li>
          </ul>
          <Switch>
            <Route exact path="/" component={Top} />{/* exactで正確にマッチしたpathに限定 */}
            <Route path="/about" component={About} />
            <Route path="/article/:id" component={Article} />
            {/* 全てにマッチしない場合はトップページを表示 */}
            <Route component={Top} />
          </Switch>
        </div>
      </Router>
    )
  }
}

export default App
import React, {Component} from 'react'

export default class Article extends Component {
    render(){
        const id = this.props.match.params.id
        const path = this.props.match.path
        const url = this.props.match.url
        return (
            <React.Fragment>
                <h1>No.{id}の記事</h1>
                <p>path: {path}</p>
                <p>url: {url}</p>
            </React.Fragment>
        )
    }
}