I wrote this quick DynamicComponent for use with React and Meteor’s Dynamic import feature:
export default class DynamicComponent extends React.Component {
constructor (props) {
super(props)
this.state = {isLoaded: false}
props.importer().then(m => {
this.setState({
isLoaded: true,
Component: m.default
})
})
}
render () {
const {isLoaded, Component} = this.state
return isLoaded && Component
? <Component {...this.props} />
: <span>Loading...</span>
}
}
DynamicComponent.propTypes = {
importer: React.PropTypes.func.isRequired
}
Use like this:
<DynamicComponent {...props} importer={() => import('./MyComponent')} />
The importer
property is a bit ugly in use - but I wanted to be able to define the path only once. Originally I tried to use a simple path
string, but that had two drawbacks:
- It couldn’t take a relative path (because the DynamicComponent definition would have to load from its own location, breaking the linkage)
- Meteor wouldn’t bundle the dynamically loaded component, because the compiler requires an intact
import('string path')
in order to know about the dynamic package, which would require a throwaway function somewhere, which is more ugly.
Anyway, what do you think?