25
17

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-domでpathのパラメータ渡しと子コンポーネントへのprops渡しを両立させる

Last updated at Posted at 2017-06-05

やりたいこと

react-routerでpathのパラメータを渡しつつ、子コンポーネントにpropsを渡すことを両立させたい。

環境

  • react-router-dom: 4.1.1

やり方

<Switch>
  <Route exact path='/' component={Home} />
  <Route path='/user/:id' render={({match}) => (
    <MyComponent {...props} match={match} />
  )} />
</Switch>

これでOK。MyComponent内でthis.props.match.params.idを受け取れる。
明示的にmatchを渡すところがポイント。

失敗例

<Route path='/user/:id' component={MyComponent} />

子コンポーネントでpropsが受け取れない。

<Route path='/user/:id' render={() => <MyComponent {...props} />} />}/>

子コンポーネントでthis.props.match.params.idがとれない

参考

25
17
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
25
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?