Stav Alfi
Stav Alfi

Reputation: 13923

Why decorator throws error of invalid type

Minimal example:

import React from 'react';
import ReactDOM from 'react-dom';


const decorator = context => WrappedComponent => <WrappedComponent context={context}/>;

@decorator(1)
class Parent extends React.Component {
    render(){
        return 1;
    }
}

ReactDOM.render(<Parent />, document.getElementById('app-root'));

Errors:

react.development.js:225 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: . Did you accidentally export a JSX literal instead of a component?

react-dom.development.js:55 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

When I remove the decorator from the top of my component, everything works great.


babel config:

"plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ]
  ] 

What is the problem with my decorator?

Upvotes: 0

Views: 459

Answers (1)

CROSP
CROSP

Reputation: 4617

Returning JSX code is not a valid expression, you should try to wrap in a class like that.

const decorator = (providedContext) => (WrappedComponent) => {
   return class extends React.Component {

      componentDidMount() {

      }
      render() {
         return <WrappedComponent context={providedContext}/>
      }
   }
}

Upvotes: 1

Related Questions