Skip to content

Instantly share code, notes, and snippets.

@itsdouges
Created September 19, 2018 07:42
Show Gist options
  • Save itsdouges/0f8b4450fd92f041ad0a67a9c5acd0ec to your computer and use it in GitHub Desktop.
Save itsdouges/0f8b4450fd92f041ad0a67a9c5acd0ec to your computer and use it in GitHub Desktop.
Create an async component that returns props.children during loading
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