How to clone multiple children using React.cloneElement?

I am trying to clone React elements like this to transfer parent details (in this example, no details are assigned):

React.createElement('div', { style: this.props.style }, React.cloneElement(this.props.children, null) ) 

This, however, returns the following error:

Inactive invariant violation: element type is invalid: a string is expected (for built-in components) or class / function (for composite components), but received: undefined.

If there is only one child, or if I pass React.cloneElement (this.props.children [0], null), then there is no error and the desired item will be displayed.

How can I clone multiple items?

+5
source share
1 answer

children props - an opaque structure, it can be undefined , an array or a single reaction element. You should use the React.Children utilities to display the children structure:

 const style = this.props.style React.createElement('div', { style }, React.Children.map(this.props.children, (child => React.cloneElement(child, { style }))) ) 
+9
source

All Articles