Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Created June 13, 2020 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlhorky/5898eb78905ef4b7197a64a132515abe to your computer and use it in GitHub Desktop.
Save karlhorky/5898eb78905ef4b7197a64a132515abe to your computer and use it in GitHub Desktop.
Find React Child in Children Recursively Using a Find Function
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;
}
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