Created
October 11, 2017 07:47
-
-
Save jmlweb/045c499a8e24afbb80aed380f68fc362 to your computer and use it in GitHub Desktop.
Dynamic Component React
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
// @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