I have a question, I have a node element like below:
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
I want to clone all span elements and adding to this new prop like onClick but also keep parent element. How I can do that with React?
Example:
React.Children.map(children, child => {
React.cloneElement(child, { onClick: handleClick })
})
no problem if there is no div
outside. But in my case I have div is a parent element outside.
CodePudding user response:
const spanElement = <span>1</span>;
<div>
{spanElement}
{React.cloneElement(spanElement)}
<span>2</span>
<span>3</span>
</div>
You need something like that.
And here you are the React clone element method explanation: https://blog.logrocket.com/using-react-cloneelement-function/