Skip to content

Instantly share code, notes, and snippets.

@Sivli-Embir
Last active June 23, 2017 16:55
Show Gist options
  • Save Sivli-Embir/ebc39ea1b24ba079bf2a68a1e9fa05f4 to your computer and use it in GitHub Desktop.
Save Sivli-Embir/ebc39ea1b24ba079bf2a68a1e9fa05f4 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