Skip to content

Instantly share code, notes, and snippets.

@jmlweb
Created October 11, 2017 07:47
Show Gist options
  • Save jmlweb/045c499a8e24afbb80aed380f68fc362 to your computer and use it in GitHub Desktop.
Save jmlweb/045c499a8e24afbb80aed380f68fc362 to your computer and use it in GitHub Desktop.
Dynamic Component React
// @flow
import React, { Component } from 'react';
import isSnapshot from '../../utils/isSnapshot';
export default function createDynamicComponent(
importComponent: () => {default: any},
requireComponent: () => {default: any},
) {
type Props = {
[name: string]: any,
};
type State = {
component: any,
};
class DynamicComponent extends Component<Props, State> {
constructor(props: Props) {
super(props);
let component = null;
if (isSnapshot()) {
component = requireComponent().default;
}
this.state = {
component,
};
}
componentDidMount() {
(async() => {
const { default: component } = await importComponent();
this.setState({
component,
});
})();
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return DynamicComponent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment