Created
June 13, 2020 11:17
-
-
Save karlhorky/5898eb78905ef4b7197a64a132515abe to your computer and use it in GitHub Desktop.
Find React Child in Children Recursively Using a Find Function
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
import React from 'react'; | |
export function findReactChildRecursively(children, findFunction) { | |
const found = React.Children.toArray(children).find(findFunction); | |
if (found) { | |
return true; | |
} else if (children?.props?.children) { | |
findReactChildRecursively(children.props.children); | |
} | |
return false; | |
} |
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
import React from 'react'; | |
import {findReactChildRecursively} from './find-react-child-recursively.js'; | |
function MyComponent({children}) { | |
// Example: find whether an MDX A tag exists within | |
// the children passed to this component | |
const foundMdxATag = findReactChildRecursively( | |
children, | |
(child) => child?.props?.mdxType === 'a', | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment