Skip to content

Instantly share code, notes, and snippets.

@zerobias
Last active November 16, 2018 20:21
Show Gist options
  • Save zerobias/2e50e3b46daffccb5cfea6dbd67f789a to your computer and use it in GitHub Desktop.
Save zerobias/2e50e3b46daffccb5cfea6dbd67f789a to your computer and use it in GitHub Desktop.
Async component
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;
}
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