Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Created October 22, 2018 06:19
Show Gist options
  • Save sagar-gavhane/e10ceb5463d3ab35719cffe9a14108ab to your computer and use it in GitHub Desktop.
Save sagar-gavhane/e10ceb5463d3ab35719cffe9a14108ab to your computer and use it in GitHub Desktop.
This code snippets is created during writting article on "Code splitting in React". article link is here => https://medium.com/@sgavhane70/code-splitting-in-react-f475a0da4c3e
// filename: asyncComponent.jsx
import React, { Component } from "react";
const asyncComponent = (getComponent) => {
// return AsyncComponent class component
return class AsyncComponent extends Component {
static Component = null;
state = {
Component: AsyncComponent.Component // first time similar to static Component = null
};
componentWillMount() {
if (!this.state.Component) {
// if this.state.Component is true value then getComponent promise resolve with .then() method
// For simplicity, I haven't caught an error, but you can catch any errors or show loading bar or animation to user etc.
getComponent().then(({ default: Component }) => {
AsyncComponent.Component = Component;
this.setState({ Component }); // update this.state.Component
});
}
}
render() {
const { Component } = this.state; // destructing Component from this.state
if (Component) {
// if Component is truthy value then return Component with props
return <Component {...this.props} />;
}
return null;
}
};
};
export default asyncComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment