-
-
Save ultim8k/83f22ff7afdb5046aad3996306568624 to your computer and use it in GitHub Desktop.
Recursively cloning React children
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { isObject } from 'lodash'; | |
export class Foo extends React.Component { | |
recursiveCloneChildren(children) { | |
return React.Children.map(children, child => { | |
if(!isObject(child)) return child; | |
var childProps = {someNew: "propToAdd"}; | |
childProps.children = this.recursiveCloneChildren(child.props.children); | |
return React.cloneElement(child, childProps); | |
}) | |
} | |
render() { | |
const { children } = this.props; | |
const clonedChildren = this.recursiveCloneChildren(children); | |
return ( | |
<div> | |
{clonedChildren} | |
</div> | |
) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment