Skip to content

Instantly share code, notes, and snippets.

@garmjs
Forked from acdlite/app.js
Last active July 31, 2017 12:37
Show Gist options
  • Save garmjs/708aee9f33559c54856e2ff1b5250854 to your computer and use it in GitHub Desktop.
Save garmjs/708aee9f33559c54856e2ff1b5250854 to your computer and use it in GitHub Desktop.
Quick and dirty code splitting with React Router v4
import React from 'react'
import { Loading } from '../components/loading'
function asyncComponent (getComponent) {
return class AsyncComponent extends React.Component {
static Component = null
mounted = false
state = {
Component: AsyncComponent.Component
};
componentWillMount () {
if (this.state.Component === null) {
getComponent().then(m => m.default).then(Component => {
AsyncComponent.Component = Component
if (this.mounted) {
this.setState({Component})
}
})
}
}
componentDidMount () {
this.mounted = true
}
componentWillUnmount () {
this.mounted = false
}
render () {
const {Component} = this.state
if (Component !== null) {
return <Component {...this.props} />
}
return <Loading />
}
}
}
export default asyncComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment