Skip to content

Instantly share code, notes, and snippets.

@manivelarjunan
Last active March 30, 2019 22:04
Show Gist options
  • Save manivelarjunan/c211a0ec3d3028ed032b6a19d3accc6e to your computer and use it in GitHub Desktop.
Save manivelarjunan/c211a0ec3d3028ed032b6a19d3accc6e to your computer and use it in GitHub Desktop.
Higher order component for for lazy loading
import React, {Component} from 'react';
const asyncComponent = (importComponent) => {
return class extends Component {
state = {
component : null
};
componentDidMount() {
// import component should be function refererce.
// it returns promise
importComponent().then(cpm => {
// it has default property to load component dynamically (cpm.default)
this.setState({component:cpm.default});
});
}
render () {
// render method renders the component dynamically.
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
}
export default asyncComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment