Search code examples
javascriptreactjswebpackwebpack-2es6-modules

Why does this react component, imported with System.import, not render?


I am trying to implement dynamic code splitting with webpack 2 and react. To test I've created a component that pulls in code asynchronously:

import React, { Component } from 'react'

export class Async extends Component {
  constructor(props) {
    super(props)
    this.state = { component: <div>Loading</div> }
  }

  componentDidMount() {
    System.import('../../about')
      .then(component => this.setState({ component: component.About }))
      .catch(error => this.setState({ component: <div>{error.message}</div> }))
  }

  render() {
    return this.state.component
  }
}

However, when I mount it, it returns the following error:

Async.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Putting a console.log(this.state.component) in Async's render function results in the following:

enter image description here

So what's going wrong here? It seems like I'm getting valid react components, so why is it throwing an error?


Solution

  • You're returning the component class, when you should actually be returning an element created from that class. They're not the same thing!

    // Replace this:
    
    render() {
        return this.state.component
    }
    
    // With this:
    
    render() {
        return <this.state.component />
    }
    
    // Or this:
    
    render() {
       return React.createElement(this.state.component)
    }