Skip to content

Instantly share code, notes, and snippets.

@rambabusaravanan
Created March 12, 2018 07:42
Show Gist options
  • Save rambabusaravanan/b71b8d6b3a8ecf89c3c3427580258c27 to your computer and use it in GitHub Desktop.
Save rambabusaravanan/b71b8d6b3a8ecf89c3c3427580258c27 to your computer and use it in GitHub Desktop.
Detect React Objects - Components and Elements
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
@iGoodie
Copy link

iGoodie commented Mar 6, 2024

Nice one! Thanks for sharing. 🎉


There's one thing tho.

&& React.isValidElement(Component())

This may fail as well, when your Component uses hooks by throwing following error:

id hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment