Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Dom Element or React Component

When creating an HOC I'm not sure which kind of component will be wrapped, sometimes it is another React Component, sometimes it could be a plain DOM Element as li and a.

WrappedComp = myHOC(BaseComponent)

MyHOC will pass extra props to the wrapped component and in most of the cases this will work as it should.

But sometimes when BaseComponent is for example an li it will not accept the extra props and React will throw a warning Unkown Prop Warning saying that DOM element do not accept non-standard dom attributes: https://facebook.github.io/react/warnings/unknown-prop.html

So how could I check if BaseComponent is a DOM element or else? In case it is I will not pass the extra props to it.

Is there a better way to do this?

like image 709
Leonardo Avatar asked Apr 12 '17 10:04

Leonardo


2 Answers

Short answer:
Check if element is of type string to check if element is a DOM element.
Check if element is of type function to check if element is a React component.

Example:

  if (typeof BaseComponent.type === 'string') {
    return BaseComponent
  }
  // add props

Long answer:
As defined in the React documentation, built-in components like <li> or <span> results in a string 'li' or 'span' being passed to React.createElement, e.g. React.createElement("li").
Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.

Consequently, a React Component is of type function, while a DOM Component is of type string.

The following WrapperComponent logs the typeof child.type of each child element. The output is function, string, string.

function WrappedComponent({children}) {
  return React.Children.map(children, child => {
    console.log(typeof child.type)
    ...
  })
}

const BaseComponent = ({children}) => children

function App() {
  return (
    <WrappedComponent>
      <BaseComponent>This element has type of function🔥</BaseComponent>
      <span>This element has type of string</span>
      <li>This element has type of string</li>
    </WrappedComponent>
  )
}
like image 187
Kaffekoppen Avatar answered Oct 12 '22 01:10

Kaffekoppen


Check if BaseComponent is a React Component, and add the required props.

if(BaseComponent.prototype.isReactComponent){
    //add props
}
like image 21
Gautham Kumaran Avatar answered Oct 12 '22 02:10

Gautham Kumaran