参考にさせていただいたページ
- React で this.props.children に新しい Props を渡す - 無駄と文化
- reactjs - How to assign the correct typing to React.cloneElement when giving properties to children? - Stack Overflow
サンプルコード
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);
としています。