Created
January 15, 2018 16:34
-
-
Save ArVan/7d498dcc0e3860f2c0f94916b320d778 to your computer and use it in GitHub Desktop.
A React HOC for loading router components upon request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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