React DynamicComponent loader (for dynamic import)

I wrote this quick DynamicComponent for use with React and Meteor’s Dynamic import feature:

export default class DynamicComponent extends React.Component {
  constructor (props) {
    this.state = {isLoaded: false}
    props.importer().then(m => {
        isLoaded: true,
        Component: m.default

  render () {
    const {isLoaded, Component} = this.state
    return isLoaded && Component
      ? <Component {...this.props} />
      : <span>Loading...</span>
DynamicComponent.propTypes = {
  importer: React.PropTypes.func.isRequired

Use like this:

<DynamicComponent {...props} importer={() => import('./MyComponent')} />

The importer property is a bit ugly in use - but I wanted to be able to define the path only once. Originally I tried to use a simple path string, but that had two drawbacks:

  1. It couldn’t take a relative path (because the DynamicComponent definition would have to load from its own location, breaking the linkage)
  2. Meteor wouldn’t bundle the dynamically loaded component, because the compiler requires an intact import('string path') in order to know about the dynamic package, which would require a throwaway function somewhere, which is more ugly.

Anyway, what do you think?


Pretty cool idea, I might give it a try. It would be much DRYer than my switch statements

1 Like

It needs better error handling, and maybe a way to select a different component than default. maybe also a way to set the loading component in some way. A way to set the className from some combo of the imported module, and the component name might we nice too (for React dev tools, and whatever else uses the component name).

I’m not sure how to do proper error handling in Meteor with React though.

I wonder if this would work inside Meteor?

React Loadable is actually a component that leverages dynamic imports. It seems to work perfectly inside Meteor! As per Ben Newman:

1 Like

React Loadable seems to eat and silence errors from the other side of the import.

Do you know if there’s a way to restrict imports based on user-roles ?

Any restriction would have to happen on the server side to be effective. That would require hooking into or over-riding whatever methods are there to do the dynamic import. I doubt it’s really set up for that, but I haven’t looked at it at all.