Categories
React Answers

How to Detect a Whether an Entity is React Component or a React Element?

Spread the love

Sometimes, we want to detect whether a React entity is a component or an element.

In this article, we’ll look at how to detect whether a React entity is a component or an element.

Detect a React Component vs. a React Element

We can check if an object is a function component by checking that it’s a function and that it contains the 'return React.createElement' code.

For instance, we can write:

const isFunctionComponent = (component) => {
  return (
    typeof component === 'function' &&
    String(component).includes('return React.createElement')
  )
}

To check for a class component we can check for type 'function' .

And we can check for the isReactComponent property in the component’s prototype .

For example, we can write:

const isClassComponent = (component) => {
  return (
    typeof component === 'function' &&
    !!component.prototype.isReactComponent
  )
}

To check if a variable is a valid element, we can use the React.isValidElement method to do that.

For example, we can write:

const isElement = (element) => {
  return React.isValidElement(element);
}

Conclusion

We can check if an object is a function component by checking that it’s a function and that it contains the 'return React.createElement' code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *