Skip to content

Instantly share code, notes, and snippets.

@eisisig
Created March 7, 2017 08:50
Show Gist options
  • Save eisisig/5cea6732a6b3f2b8ad4727b84427e167 to your computer and use it in GitHub Desktop.
Save eisisig/5cea6732a6b3f2b8ad4727b84427e167 to your computer and use it in GitHub Desktop.
example of asyncRoute
import React from 'react'
import nprogress from 'nprogress'
import loadJS from 'fg-loadjs'
import LoaderSpinner from '../components/LoaderSpinner'
import preserver from './Preserver'
let firstRoute = true;
function asyncRoute(getComponent) {
return class AsyncComponent extends React.Component {
static Component = null;
mounted = false;
state = {
Component: AsyncComponent.Component
};
componentWillMount() {
document.documentElement.scrollTop = 0;
if ( this.state.Component === null ) {
if ( !firstRoute ) {
nprogress.start();
}
getComponent().then(m => m.default).then(Component => {
if ( firstRoute ) {
firstRoute = false;
if ( process.env.NODE_ENV === 'production' ) {
loadJS('https://www.google-analytics.com/analytics.js');
}
} else {
nprogress.done();
}
AsyncComponent.Component = Component;
if ( this.mounted ) {
this.setState({Component});
}
})
}
}
componentDidMount() {
this.mounted = true;
}
componentWillUnmount() {
this.mounted = false;
}
render() {
const {Component} = this.state;
const {location} = this.props;
if ( Component !== null ) {
if ( process.env.NODE_ENV === 'production' ) {
ga('send', 'pageview', `${location.pathname}${location.search}`);
}
return <Component {...this.props} />
}
if ( preserver.has() ) {
return preserver.render();
} else {
return (
<div className="container text-xs-center" style={{padding:'25vh 0'}}>
<LoaderSpinner size={128} delay={true} />
</div>
)
}
}
}
}
// export const Home = asyncRoute(() => System.import('./home'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment