Last active
September 23, 2019 19:36
-
-
Save gilbarbara/f99b612b65954c3e3339ca142fab946d to your computer and use it in GitHub Desktop.
Map React Children Recursively
This file contains 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
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