0
0

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 3 years have passed since last update.

Reactを学んだ(3) ~React Router~

Last updated at Posted at 2020-11-28

React Router

  • SPAを実現してくれる。
  • <BrowseRouter/><Link/><Route/>を同時に使う。
  • yarn add react-router-domから始める。

<BrowserRouter />

  • こんな感じで導入する。
  • 遷移の履歴がhistoryオブジェクトの中に蓄積されるようだ。
src/index.js
import { BrowserRouter } from 'react-router-dom'
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>, document.getElementById('root')
);

<Link to="/about">About</Link>

  • 公式ドキュメントはこちら
  • stateが肝っぽい。

image.png

  • 現在地を元に次の行き先を決めるためにはcallback関数を渡せば良いらしい。

image.png

<Route />

  • This is a component which is going to decide which components are rendered based on the current URL path.
  • ブラウザが指定するURLがpath=XXXにマッチした場合のみ、指定されたコンポーネントを描画してくれる。
  • 以下のように使用する
import { Link } from 'react-router-dom'

<div>
  <Route exact path='/' render={() => (   // exactを付けないと前方一致は全て当てはまってしまう...
                                          // propsを渡す必要があるならば、render=にcallback関数形式でコンポーネントを指定する
    <ListContacts
      onDeleteContact={this.removeContact}
      contacts={this.state.contacts}
    />
  )} />

  <Route path='/create' component={CreateContact}/>   // propsを渡す必要がなければ、component=XXXで指定できる
</div>

  • また、以下のようにhistory.push('/xxx')により、ページのリダイレクトが可能である。


<Route path='/create' render={({ history }) => (  // 第一引数はhistroyオブジェクトが渡されるらしい(?)
  <CreateContact
    onCreateContact={(contact) => {
      this.createContact(contact)
      history.push('/')              // history.push('/xxx')を指定する
    }}
  />
)}/>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?