Skip to content

Instantly share code, notes, and snippets.

@usirin
Created April 12, 2019 20:03
Show Gist options
  • Save usirin/303a827af5b1eef4b00255d329812edc to your computer and use it in GitHub Desktop.
Save usirin/303a827af5b1eef4b00255d329812edc to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
const URL_MAP = {
blue: 'http://localhost:5000/build/index.js',
orange: 'http://localhost:5001/build/index.js',
}
const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1)
const loaded = {}
const load = src => {
return new Promise(resolve => {
if (loaded[src]) return resolve()
const script = document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', src)
script.onload = (...args) => {
loaded[src] = true
resolve(...args)
}
document.head.appendChild(script)
})
}
class App extends Component {
state = { Component: null }
onClick = color => e => {
e.preventDefault()
const url = URL_MAP[color]
console.log({ url, color })
load(url).then(() => this.setState({ Component: capitalize(color) }))
}
render() {
const Component = window[this.state.Component]
return (
<div className="App">
<button onClick={this.onClick('blue')}>Load Blue</button>
<button onClick={this.onClick('orange')}>Load Orange</button>
{Component && <Component />}
</div>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment