LoginSignup
25
15

More than 5 years have passed since last update.

React.cloneElementでpropsを追加する

Last updated at Posted at 2016-01-24

tl;dr

Reactのchildrenに特定のpropsを追加したい時は、React.cloneElementを使う。

やりたいこと

<Dialog closeEvent='onFinish'>
  <RegistrationForm/>
</Dialog>

Dialogはモーダルダイアログっぽく表示するコンポーネントで、中のRegistrationFormは登録フォームでいろんなところで使える再利用可能な感じに仕上がってるものとする。Dialog自体としては標準で閉じるボタンを表示するものの、登録フォームでの処理が終わったら自動で閉じたい、なんてこともあるはず。

とはいえ、RegistrationForm自体はDialog内で使われることを意識してないので、処理が成功したらモーダルダイアログを閉じる処理をRegistrationForm自体に入れるわけにもいかない。

Dialogchildrenとして渡されたコンポーネントの特定のイベントに対して、モーダルダイアログを閉じる処理を設定すればよさそうだが、childrenのpropsにどうやって後から指定すれば良いのか。

React.cloneElement

:ok:
https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

既存のpropsに新しいpropsをマージすることができる。

render() {
  return React.cloneElement(
    this.props.children,
    {マージしたいprops}
  );
}

てな感じである。

こちらのfiddleに実装してみた。細かい制御はないが、Content自体に一切Dialog内にあることを意識させずに、Dialogを閉じる処理を追加できている。
https://jsfiddle.net/hokuma/1mu5opr4/

25
15
2

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
15