Created
June 28, 2016 17:59
-
-
Save iammerrick/d64d9638ad6109be3736464fef5a8852 to your computer and use it in GitHub Desktop.
Offer both a higher order component and a component for lazily loading modules.
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 from 'react'; | |
const toPromise = (load) => (new Promise((resolve) => ( | |
load(resolve) | |
))); | |
class LazilyLoad extends React.Component { | |
constructor() { | |
super(...arguments); | |
this.state = { | |
isLoaded: false | |
}; | |
} | |
componentWillMount() { | |
this.load(this.props); | |
} | |
componentWillReceiveProps(next) { | |
this.load(next); | |
} | |
load(props) { | |
this.setState({ | |
isLoaded: false | |
}); | |
const { modules } = props; | |
const keys = Object.keys(modules); | |
Promise.all(keys.map((key) => toPromise(modules[key]))) | |
.then((values) => (keys.reduce((agg, key, index) => { | |
agg[key] = values[index]; | |
return agg; | |
}, {}))) | |
.then((result) => { | |
this.setState({ modules: result, isLoaded: true }); | |
}); | |
} | |
render() { | |
if (!this.state.isLoaded) return null; | |
return this.props.children(this.state.modules); | |
} | |
} | |
LazilyLoad.propTypes = { | |
children: React.PropTypes.func.isRequired | |
}; | |
export const LazilyLoadFactory = (Component, modules) => { | |
return (props) => ( | |
<LazilyLoad modules={modules}> | |
{(mods) => <Component {...mods} {...props} />} | |
</LazilyLoad> | |
); | |
}; | |
export default LazilyLoad; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment