Skip to content

Instantly share code, notes, and snippets.

@MaximeHeckel
Last active August 17, 2018 20:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MaximeHeckel/40bf6b53fc71ef63d4132d57a8e07987 to your computer and use it in GitHub Desktop.
Save MaximeHeckel/40bf6b53fc71ef63d4132d57a8e07987 to your computer and use it in GitHub Desktop.
Medium - React "sub-components" - findByType function
import React from 'react';
const findByType = (children, component) => {
const result = [];
/* This is the array of result since Article can have multiple times the same sub-component */
const type = [component.displayName] || [component.name];
/* We can store the actual name of the component through the displayName or name property of our sub-component */
React.Children.forEach(children, child => {
const childType =
child && child.type && (child.type.displayName || child.type.name);
if (type.includes(childType)) {
result.push(child);
}
});
/* Then we go through each React children, if one of matches the name of the sub-component we’re looking for we put it in the result array */
return result[0];
};
export default findByType;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment