Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

Reactのchildrenにpropsを渡す

参考にさせていただいたページ

サンプルコード

import { cloneElement, Children, ReactElement } from 'react';

const HogeExample: React.FC = ({ children }) => {
  const additionalProps = { hoge: 'hoge' };

  const childrenWithAdditionalProps = Children.map(children, (child) => {
    switch (typeof child) {
      case 'string':
        // 子要素がテキストノードだった場合はそのまま return
        return child;

      case 'object':
        // React要素だった場合は newProps を渡す
        return cloneElement(child as ReactElement<any>, additionalProps);

      default:
        // それ以外の場合はとりあえず null 返しとく
        return null;
    }
  });

  return <form>{childrenWithAdditionalProps}</form>;
};

export default HogeExample;

サンプルコードのchildの型について

そのままだとエラーになっていたため、「 reactjs - How to assign the correct typing to React.cloneElement when giving properties to children? - Stack Overflow 」を参考に return cloneElement(child as ReactElement<any>, additionalProps); としています。