39
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React Routerのパスにパラメータを渡す

Posted at

一つ前の記事の続きです。
React Routerを使ってみる

メンバー一覧のようなものを作って、メンバーのIDをパラメータとして渡し、対応するIDのユーザーを表示させてみます。

src/MembersList.js
import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch
} from 'react-router-dom'

const members = [
  {id: 1, name: 'Hisashi', info: 'リードギター'},
  {id: 2, name: 'TERU', info: 'ボーカル'},
  {id: 3, name: 'TAKURO', info: 'ギター'},
  {id: 4, name: 'JIRO', info: 'ベース'},
]

const MemberListApp = () => (
  <Router>
    <div style={{margin: 20}}>
      <div>
        <Switch>
          <Route path='/user/:id' component={MemberInfo} />
          <Route component={MemberList} />
        </Switch>
      </div>
    </div>
  </Router>
)

const Header = () => (
  <h1>メンバーリスト</h1>
)

class MemberList extends React.Component {
  render () {
    const memberList = members.map(e => (
      <li key={e.id}>
        <Link to={'/user/' + e.id}>{e.name}</Link>
      </li>
    ))
    return (
      <div>
        <Header />
        <ul>{memberList}</ul>
      </div>
    )
  }
}

class MemberInfo extends React.Component {
  render () {
    const {params} = this.props.match
    const id = parseInt(params.id, 10)
    const member = members.filter(e => e.id === id)[0]
    return (
      <div>
        <div>{id}: {member.name} - {member.info}</div>
        <hr />
        <div><MemberList /></div>
        <div><Link to='/'>TOP</Link></div>
      </div>
    )
  }
}

export default MemberListApp

<Route path='/user/:id' component={MemberInfo} />の部分ですが、componentを使った場合、routerはReactのエレメントを作成するために、React.createElementを実行します。

ReactTraining/react-router

index.jsにレンダリングメソッドを追加します。

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import MemberListApp from './MembersList'
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(<MemberListApp />, document.getElementById('memberList'));
registerServiceWorker();

public/index.html<div id="memberList"></div>を追加します。

ブラウザの動きはこのようになります。

screencast 2018-01-08 13-30-06.gif

39
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?