Created
October 22, 2018 06:19
-
-
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
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
// 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