Skip to content

Instantly share code, notes, and snippets.

@AlexFrazer
Created March 6, 2017 20:41
Show Gist options
  • Save AlexFrazer/4914830ed7612872ae80f6393d261d1e to your computer and use it in GitHub Desktop.
Save AlexFrazer/4914830ed7612872ae80f6393d261d1e to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from 'react';
export default class LazilyLoad extends Component {
static propTypes = {
modules: PropTypes.object,
children: PropTypes.func.isRequired,
};
static defaultProps = { modules: {} };
state = {
modules: {},
isLoaded: false,
};
componentDidMount() { this.load(); }
componentDidUpdate(previous) {
if (this.props.modules !== previous.modules) {
this.load();
}
}
async load() {
this.setState({ isLoaded: false, modules: {} });
const loaded = {};
for (const [name, load] of Object.entries(this.props.modules)) {
const { default: LoadedModule } = await load();
loaded[name] = LoadedModule;
}
this.setState({ isLoaded: true, modules: loaded });
}
render() {
if (!this.state.isLoaded) return null;
return React.Children.only(this.props.children(this.state.modules));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment