Skip to content

Instantly share code, notes, and snippets.

@fael
Created September 22, 2017 16:28
Show Gist options
  • Save fael/b828421d1a4a7b04a4502821b688d13f to your computer and use it in GitHub Desktop.
Save fael/b828421d1a4a7b04a4502821b688d13f to your computer and use it in GitHub Desktop.
Async Component Loading for React
// @flow
import React, { Component } from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import asyncComponent from './asyncComponent'
const MyAwesomePage = asyncComponent(() => import('./MyAwesomePage'))
/**
* Main Component, displays App Shell UI, setup routes which are dynamically loaded
*/
export default class App extends Component<{}> {
render() {
return (
<AppShell>
<BrowserRouter>
<Switch>
<Route component={MyAwesomePage} />
</Switch>
</BrowserRouter>
</AppShell>
)
}
}
// @flow
import * as React from 'react'
type Props = {}
type State = {
component: ?React.ComponentType<any>
}
type DefaultExportedCmp = {
default: React.ComponentType<any>
}
/**
* Component that allows import()'ed components to be returned as Promises
* Useful for code chunking/splitting
* Ref:
*/
export default function asyncComponent(
importComponent: () => Promise<DefaultExportedCmp> | DefaultExportedCmp
) {
class AsyncComponent extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
component: null
}
}
componentDidMount() {
this.getComponent()
}
async getComponent() {
const { default: component } = await importComponent()
this.setState({
component: component
})
}
render() {
const C = this.state.component
return C ? <C {...this.props} /> : null
}
}
return AsyncComponent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment