Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  114] [ 7]  / answers: 1 / hits: 27171  / 8 Years ago, fri, june 24, 2016, 12:00:00

I try to clone React elements like this, to pass the parent props to them (the props are not assigned in this example):



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


This however returns following error:




Uncaught Invariant Violation: Element type is invalid: expected a
string (for built-in components) or a class/function (for composite
components) but got: undefined.




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



How can I clone multiple elements?


More From » reactjs

 Answers
8

children props is an opaque structure, it can be undefined, an array, or a single react element. You should use the React.Children utilities to map over the children structure :



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

[#61654] Wednesday, June 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joannam

Total Points: 331
Total Questions: 106
Total Answers: 105

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
;