Skip to content

Instantly share code, notes, and snippets.

@rainstormza
Created April 3, 2018 10:55
Show Gist options
  • Save rainstormza/b39dd04ed11e6e0025765aefb9ff77eb to your computer and use it in GitHub Desktop.
Save rainstormza/b39dd04ed11e6e0025765aefb9ff77eb to your computer and use it in GitHub Desktop.
Code Splitting React js
// Dynamically imported components
const RegisterPage = asyncComponent(() =>
import('./register/RegisterPage').then(module => module.default)
)
const SearchPage = asyncComponent(() =>
import('./search/SearchPage').then(module => module.default)
)
const ReportPage = asyncComponent(() =>
import('./report/ReportPage').then(module => module.default)
)
<Route path="/" exact render={() => <Redirect to="/register" />} />
<Route path="/register" component={Routes.RegisterPage} />
<Route path="/search" component={Routes.SearchPage} />
<Route path="/report" component={Routes.ReportPage} />
import React, { Component } from "react";
export default function asyncComponent(getComponent) {
class AsyncComponent extends Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentWillMount() {
if (!this.state.Component) {
getComponent().then(Component => {
AsyncComponent.Component = Component
this.setState({ Component })
})
}
}
render() {
const { Component } = this.state
if (Component) {
return <Component {...this.props} />
}
return null
}
}
return AsyncComponent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment