Last active
November 16, 2018 20:21
-
-
Save zerobias/2e50e3b46daffccb5cfea6dbd67f789a to your computer and use it in GitHub Desktop.
Async component
This file contains hidden or 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"; | |
export default function asyncComponent(importComponent) { | |
class AsyncComponent extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
component: null | |
}; | |
} | |
async componentDidMount() { | |
try { | |
const { default: component } = await importComponent(); | |
this.setState({ | |
component: component | |
}); | |
} catch (err) {} | |
} | |
render() { | |
const C = this.state.component; | |
return C ? <C {...this.props} /> : null; | |
} | |
} | |
return AsyncComponent; | |
} |
This file contains hidden or 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 } from 'react-router-dom'; | |
import asyncComponent from './AsyncComponent'; | |
const AsyncLanding = asyncComponent(() => import('./containers/Landing')); | |
const AsyncItemView = asyncComponent(() => import('./containers/ItemView')); | |
class App extends Component { | |
render() { | |
return ( | |
<> | |
<Route exact path="/" component={AsyncLanding} /> | |
<Route exact path="/category/:category" component={AsyncLanding} /> | |
<Route exact path="/category/:category/:id" component={AsyncItemView} /> | |
</> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment