Skip to content

Instantly share code, notes, and snippets.

@ArVan
Created January 15, 2018 16:34
Show Gist options
  • Save ArVan/7d498dcc0e3860f2c0f94916b320d778 to your computer and use it in GitHub Desktop.
Save ArVan/7d498dcc0e3860f2c0f94916b320d778 to your computer and use it in GitHub Desktop.
A React HOC for loading router components upon request
import React, {Component} from 'react';
const asyncComponent = (importComponent) => {
class Comp extends Component {
state = {
component: null
}
componentDidMount() {
importComponent()
.then(cmp => {
this.setState({component: cmp.default});
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props}/> : null;
}
}
return Comp;
};
export default asyncComponent;
import React, {Component} from 'react';
import {Route, Switch, Redirect, withRouter} from 'react-router-dom';
import HomePage from './containers/HomePage';
const AsyncUserPage = asyncComponent(() => {
return import('./containers/UserPage');
});
class Routes extends Component {
render() {
return (
<Switch>
<Route exact path='/' component={HomePage}/>
<Route exact path='/user' component={AsyncUserPage}/>
</Switch>
);
}
}
export default Routes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment