Created
September 19, 2018 07:42
-
-
Save itsdouges/0f8b4450fd92f041ad0a67a9c5acd0ec to your computer and use it in GitHub Desktop.
Create an async component that returns props.children during loading
This file contains 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'; | |
// async-component.js | |
export default ({ resolve }) => class AsyncComponent extends React.Component { | |
state = { Component: undefined }; | |
componentDidMount() { | |
resolve().then(Component => { | |
this.setState({ Component }); | |
}); | |
} | |
render() { | |
if (this.state.Component) { | |
return ( | |
<Component {...this.props}> | |
{this.props.children} | |
</Component> | |
} | |
return this.props.children; | |
} | |
} | |
// component.js | |
export default (props) => <div>{props.children}</div>; | |
// usage.js | |
import Component from './component.js'; | |
import createAsyncComponent from './async-component.js'; | |
const AsyncComponent = createAsyncComponent({ resolve: () => import('./async-component.js').then(module => module.default) }); | |
export default () => ( | |
<AsyncComponent> | |
this text will be shown regardless of async component being loaded or not | |
</AsyncComponent> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment