React&TypeScriptで入れ子コンポーネントに新たなpropsを渡す

概要
React&TypeScriptでコンポーネントを入れ子にした際に、親コンポーネントで追加のpropsを渡したいときどうするんやって話。

# 呼び出し元
<Parent>
  <Child name={name} />
</Parent>

# 親コンポーネント(Parent)
## Childコンポーネントにnameじゃない新しい引数渡したい!!!
<div>
  {this.props.children}
</div>

方法
React.cloneElementの第2引数に渡したい引数を渡せば良いだけ!
上のメソッドはObjectにしか効かないようなので、Children.mapを使ってstring、それ以外を裁く。
これで呼び出し元ではChildコンポーネントにname引数しか渡してないのにnewProps引数を扱うことができる!!!!!

import * as React from "react";
import { Children } from "react";

class Parent extends React.Component<Props, State> {
  public render() {
    const newProps = {newName: "aa"}
    const childrenWithProps = Children.map(
      this.props.children,
      (child) => {
        switch (typeof child) {
          case "string":
            return child;
          case "object":
            return React.cloneElement(child as React.ReactElement<any>, { newProps });
          default:
            return null;
        }
      },
    );
    return (
      <div>
        {childrenWithProps}
      </div>
    );
}

まとめ
基本的には以下サイトを参考に書いただけです。TypeScriptなのでchildをcastしないと怒られましたがそれ以外は一緒のやーつ
https://blog.mudatobunka.org/entry/2016/08/14/182333

この記事が気に入ったらサポートをしてみませんか?