LoginSignup
2
2

More than 5 years have passed since last update.

react-router で子Routeコンポーネントにpropsを渡す方法

Posted at

以下のバージョンで動作確認してます。

  • react: 15.4.1
  • react-router: 3.0.0

例えばこんなRoutesを定義していて、 Parent コンポーネントから Childコンポーネントをpropsとして渡したいとします。

<Router history={browserHistory}>
  <Route path="/" component={Parent}>
    <Route component={Child} />
  </Route>
</Router>

普通ならParentコンポーネント内で以下のように子コンポーネントを呼び出します。

{this.props.children}

ただ、このままではpropsを渡せません。
ですが以下のように React.cloneElementを使うことによってpropsを渡すことができます。

{React.cloneElement(this.props.children, {
    props_to_pass: this.state.props_to_pass
})}

やっていることは、 this.props.childrenReact.cloneElementでクローンしたオブジェクトを作成し、
それに対してpropsを適用しています。

なるべく状態は一つのコンポーネントにまとめたい、と感じることは多々あると思いますので、そんな時に便利です。
ただ、いかんせんあんまり美しくない方法なので、もしこれより綺麗なやり方があればお教えいただけると嬉しいです。

2
2
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
2
2