Skip to content

Instantly share code, notes, and snippets.

@gilbarbara
Last active September 23, 2019 19:36
Show Gist options
  • Save gilbarbara/f99b612b65954c3e3339ca142fab946d to your computer and use it in GitHub Desktop.
Save gilbarbara/f99b612b65954c3e3339ca142fab946d to your computer and use it in GitHub Desktop.
Map React Children Recursively
interface IOptions {
predicate: (child: React.ReactChild) => boolean;
props: { [key: string]: any };
}
function mapReactChildrenRecursively(children: React.ReactNode, options: IOptions): React.ReactNode {
if (!options.predicate || !options.props) {
return children;
}
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if (options.predicate(child)) {
return React.cloneElement(child, {
children: mapReactChildrenRecursively(child.props.children, options),
...options.props,
});
}
if (child.props.children) {
return React.cloneElement(child, { children: mapReactChildrenRecursively(child.props.children, options) });
}
return child;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment