Last active
May 6, 2020 19:21
-
-
Save magbicaleman/6776adbf4c3c4e651440ea0ba8de157c to your computer and use it in GitHub Desktop.
Crude Dynamic Import Example on Create React App index.js scaffold
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 ReactDOM from 'react-dom'; | |
import './index.css'; | |
import registerServiceWorker from './registerServiceWorker'; | |
class Dynamic extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { module: null }; | |
} | |
componentDidMount() { | |
const { path } = this.props; | |
import(`${path}`) | |
.then(module => this.setState({ module: module.default })) | |
} | |
render() { | |
const { module: Component } = this.state; // Assigning to new variable names @see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment | |
return( | |
<div> | |
{Component && <Component />} | |
</div> | |
) | |
} | |
} | |
ReactDOM.render(<Dynamic path='./App' />, document.getElementById('root')); | |
registerServiceWorker(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment