chipit24
chipit24

Reputation: 6987

ReactJS invalid component type

Looking at the "Choosing the Type at Runtime" section in the ReactJS docs, it looks like the following code should work:

class App extends Component {
  constructor() {
    super();

    this.state = { test: <div>Test</div>};
  }

  render() {
    const Test = this.state.test;

    return <Test />;
  }
}

However, nothing is rendered, and in the console I see the following error:

warning.js:36 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `App`.

I don't understand why this doesn't work; please explain.

Note that the above test app was created using create-react-app.

Upvotes: 0

Views: 225

Answers (1)

Josh Kelley
Josh Kelley

Reputation: 58342

This creates an element - a particular instance of a DOM node to be rendered to screen.

this.state = { test: <div>Test</div>};

This takes that element and tries to treat it as a component - a React function or class that knows how to render itself as an element.

const Test = this.state.test;
return <Test />;

To use an analogy from traditional OO, this would be analogous to taking a class instance and trying to use it as a class.

Something like this should work instead:

this.state = { test: <div>Test</div>};
// ...
return this.state.test;

For more information, see "React Components, Elements, and Instances."

Upvotes: 2

Related Questions