Created
March 6, 2017 20:41
-
-
Save AlexFrazer/4914830ed7612872ae80f6393d261d1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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