Created
March 12, 2018 07:42
-
-
Save rambabusaravanan/b71b8d6b3a8ecf89c3c3427580258c27 to your computer and use it in GitHub Desktop.
Detect React Objects - Components and Elements
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
function isClassComponent(component) { | |
return typeof component === 'function' | |
&& !!component.prototype.isReactComponent | |
} | |
function isFunctionComponent(component) { | |
return typeof component === 'function' | |
// && !!String(component).includes('return React.createElement') // may fails | |
&& React.isValidElement(Component()) | |
} | |
function isReactComponent(component) { | |
return isClassComponent(component) || isFunctionComponent(component) | |
} | |
function isElement(element) { | |
return React.isValidElement(element); | |
} | |
function isDOMTypeElement(element) { | |
return isElement(element) && typeof element.type === 'string'; | |
} | |
function isCompositeTypeElement(element) { | |
return isElement(element) && typeof element.type === 'function'; | |
} | |
// As suggested in https://stackoverflow.com/questions/33199959/how-to-detect-a-react-component-vs-a-react-element |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one! Thanks for sharing. 🎉
There's one thing tho.
This may fail as well, when your Component uses hooks by throwing following error: