Skip to content

Instantly share code, notes, and snippets.

@thekhairul
Last active September 17, 2021 17:00
Show Gist options
  • Save thekhairul/80c42b0fcf8c756f77c461b180a120f9 to your computer and use it in GitHub Desktop.
Save thekhairul/80c42b0fcf8c756f77c461b180a120f9 to your computer and use it in GitHub Desktop.
Modify React children while rendering
// modify react childrens while rendering in class component (can also be done in FCs)
render() {
if (this.props.children) {
return React.Children.map(this.props.children, (childElement) => {
if (childElement.type === 'string') return childElement; // return non React components as it is
return React.cloneElement(childElement, {
// pass additional props implicitly to the child react components
prop1: this.state.prop1,
prop2: this.prop2
})
});
}
}
// find all react functional child components or certain ones from a nested structure
const flattenReactFunctionalChildren = (children, type = 'function') => {
const result = [];
const traverseReactChildren = (children, type) => {
React.Children.forEach(children, (child) => {
if ((type === 'function' && typeof child.type === type) || (child.type && child.type.name === type)) {
result.push(child);
}
if (child.props && child.props.children) {
traverseReactChildren(child.props.children, type);
}
});
}
traverseReactChildren(children, type);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment