In React, components (typically referring to class components or function components) and elements are conceptually distinct:
- React Component: Serves as the blueprint for constructing React elements. It can be a class or a function that accepts props and returns React elements, indicating what should be rendered on the screen.
- React Element: Represents an immutable object description in a React application, which is the instantiation result of a component, typically created using JSX or
React.createElement.
Detecting them can be done as follows:
Detecting React Components
To determine if a variable is a React component, check its type and properties. For example, class components typically have the isReactComponent property on their prototype, while function components are functions without this property.
javascriptfunction isReactComponent(component) { // Class components are characterized by having the `isReactComponent` property on their prototype return ( component.prototype && component.prototype.isReactComponent ) || ( // Function components may be pure functions; verify they are not constructors for standard HTML elements typeof component === 'function' && String(component).includes('return React.createElement') ); }
Note that this function may not be robust in certain cases, as function components may not include the string return React.createElement, especially if they directly return JSX.
Detecting React Elements
To determine if an object is a React element, check if it has a specific $$typeof property. React element objects typically have a $$typeof property whose value is Symbol.for('react.element').
javascriptfunction isReactElement(element) { return ( element !== null && typeof element === 'object' && element.$$typeof === Symbol.for('react.element') ); }
Using Symbol.for('react.element') for comparison is the officially recommended approach by React, as this symbol serves as an internal marker for React elements, distinguishing them from regular objects.
Remember that these methods may not be entirely accurate, and their behavior may change with updates to the React library. In practice, it is typically known implicitly whether something is a component or an element based on its usage context, rather than through such detection methods.