Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Forked from dandelany/gist:1ff06f4fa1f8d6f89c5e
Last active April 26, 2018 09:42
Show Gist options
  • Save ultim8k/83f22ff7afdb5046aad3996306568624 to your computer and use it in GitHub Desktop.
Save ultim8k/83f22ff7afdb5046aad3996306568624 to your computer and use it in GitHub Desktop.
Recursively cloning React children
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