Last active
September 17, 2021 17:00
-
-
Save thekhairul/80c42b0fcf8c756f77c461b180a120f9 to your computer and use it in GitHub Desktop.
Modify React children while rendering
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
// 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