React.createElement, getting error 'Invalid hook call. Hooks can only be called inside of the body of a function component'

Viewed 345

I have a modal and the way the modal renders the component inside is through this:

     get displayModalBody() {
         const {newComponent} = this.props
         return(
             <div>
                {React.createElement(newComponent, this.props)}
             </div>
         )

      }

the only issue is that one of the elements being created has a child that is a functional component and uses hooks. So when I use the above, I get the error

Invalid 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

However... if I hardcode my Component in like so:

   get displayModalBody() {
     return(
         <div>
           <HardcodedComponent {...this.props}/>
         </div>
     )

  } 

I no longer get the error and it works as expected. The only issue is I cant hardcode the component bc it changes... anyone know why React.createElement method isn't working in this situation and any solutions?

0 Answers
Related