Skip to content

Instantly share code, notes, and snippets.

@Morganjackson
Forked from Sivli-Embir/App.js
Created March 29, 2017 21:20
Show Gist options
  • Select an option

  • Save Morganjackson/d87995b1573139f1a731f4e15e007e45 to your computer and use it in GitHub Desktop.

Select an option

Save Morganjackson/d87995b1573139f1a731f4e15e007e45 to your computer and use it in GitHub Desktop.
A drop in solution to getting dynamic import React components in Meteor 1.5
import React from 'react';
import AsyncComponent from './AsyncComponent'
// call this.getAsyncComponent(path) to get a default export.
// call this.getAsyncComponent(path, specifier) to get a non-default export.
class App extends AsyncComponent {
render() {
let view;
if (this.props.showA) {
const ExampleA = this.getAsyncComponent('/client/components/exampleA');
view = <ExampleA />
} else {
const ExampleB = this.getAsyncComponent('/client/components/exampleB');
view = <ExampleB />
}
return view;
}
}
import React from 'react';
export default class AsyncComponent extends React.Component {
constructor() {
super()
this.__AsyncComponents__ = {}
}
getAsyncComponent(name) {
if (!this.__AsyncComponents__[name]) {
getComponent(name).then(Component => {
let __AsyncComponents__ = this.__AsyncComponents__
__AsyncComponents__[name] = Component
this.forceUpdate()
})
}
//you can tweek the div to be a loader Component or something
return this.__AsyncComponents__[name] || (() => (<div />));
}
}
async function getComponent(name, specifier = 'default') {
let importObj = await import(name);
return importObj[specifier]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment