React.isValidElement
tests true for both React components as well as React elements. How would I test, specifically, that an object is a React component? Curren
If you want to know what class you have for a particular instance of an object variable, then what you want is the instanceof operator...
function isHTMLElement(obj) {
return (obj instanceof HTMLElement);
}
I tested with both document.createElement('div')
(returns true) and <someReactJSComponent />
(returns false).
instanceof
is a powerful and useful tool in JavaScript. Check out the official MDN documentation for it: Mozilla Documentation Network: instanceof
"The instanceof operator tests the presence of constructor.prototype in object's prototype chain."
In addition, I have uploaded a code sample with a code-sandbox online to demonstrate the above principle...
Online Code Sandbox :
https://codesandbox.io/s/kmxjq27ol5
Code :
function App() { return (//insert JSX here//);};
const app = App();
const ele = document.createElement("div");
const rootElement = document.getElementById("root");
ReactDOM.render(app, rootElement);
console.log(
"Hello! Is a React Component HTML???" +
(app instanceof HTMLElement) +
"| Is an HTML element HTML???" +
(ele instanceof HTMLElement) +
"|"
);
Code Results :
Hello! Is a React Element HTML???false| Is an HTML element HTML???true|
No problem (tested Chrome and FF). Just use instanceof
.