Last active
August 17, 2018 20:02
-
-
Save MaximeHeckel/40bf6b53fc71ef63d4132d57a8e07987 to your computer and use it in GitHub Desktop.
Medium - React "sub-components" - findByType 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'; | |
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