Created
September 27, 2019 10:15
-
-
Save liamtarpey/2ad267afef61cfd0ea983f0ce57f519f to your computer and use it in GitHub Desktop.
Loadable Components in React
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment