Created
September 20, 2019 15:31
-
-
Save liamtarpey/44bd22f6cec75b5dc6a28396fd6a088b to your computer and use it in GitHub Desktop.
Busuu Code Splitting
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, { PureComponent, Suspense, Fragment, lazy } from 'react'; | |
import LoadableErrorBoundary from './LoadableErrorBoundary.jsx'; | |
import LoadableConstants from './loadable.constants.js'; | |
// Private vars | |
const filename = 'LoadableComponent.jsx'; | |
/** | |
* Our render for any loading state - maybe add a nice spinner? | |
* (Visible whilst the component is being fetched) | |
*/ | |
const loadingState = ( | |
<div>Loading...</div> | |
); | |
const LoadComponent = (comp) => { | |
if (!LoadableConstants[comp]) { | |
throw `${filename} - '${comp}' cannot be found in the loadables list.`; | |
} | |
return class CreateComponent extends PureComponent { | |
constructor(props) { | |
super(); | |
this.hasMounted = false; | |
this.state = { component: null }; | |
this.loadChunk = this.loadChunk.bind(this); | |
this.stateSetter = this.stateSetter.bind(this); | |
} | |
componentDidMount() { | |
this.hasMounted = true; | |
this.loadChunk(); | |
} | |
componentWillUnmount() { | |
this.hasMounted = false; | |
} | |
loadChunk() { | |
this.stateSetter({ component: lazy(LoadableConstants[comp]) }); | |
} | |
stateSetter(stateParams) { | |
this.hasMounted && this.setState(stateParams); | |
} | |
render() { | |
if (!this.state.component) { | |
return (null); | |
} | |
return ( | |
<LoadableErrorBoundary onRetry={this.loadChunk}> | |
<Suspense fallback={loadingState}> | |
<this.state.component {...this.props} /> | |
</Suspense> | |
</LoadableErrorBoundary> | |
); | |
} | |
} | |
}; | |
export default LoadComponent; |
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
export default { | |
HomeComponent: () => import(/* webpackChunkName: 'home/HomeComponent' */ './HomeComponent.jsx'), | |
AboutComponent: () => import(/* webpackChunkName: 'about/AboutComponent' */ './AboutComponent.jsx'), | |
SettingsComponent: () => import(/* webpackChunkName: 'settings/SettingsComponent' */ './SettingsComponent.jsx') | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment