Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone multiple children with React.cloneElement?

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?

like image 372
Jaakko Karhu Avatar asked Jun 24 '16 10:06

Jaakko Karhu


People also ask

How do you clone children in React?

We can use React. cloneElement() method when a parent component wants to add or modify the props of its children. The React. cloneElement() function creates a clone of a given element, and we can also pass props and children in the function.

Can we render two child components in React?

React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components. Prerequisites: The pre-requisites for this project are: React Knowledge.

What is the difference between createElement and cloneElement?

createElement is the code that JSX gets compiled or converted into and is used by reacting to create elements. cloneElement is used for cloning elements and passing them new props. This method is used to describe how the User Interface looks. This method is used to manipulate the elements.

Should you use React cloneElement?

React. cloneElement() is useful when you want to add or modify the props of a parent component's children while avoiding unnecessary duplicate code.


1 Answers

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 })))
)
like image 153
Pierre Criulanscy Avatar answered Sep 28 '22 08:09

Pierre Criulanscy