Created
September 16, 2016 14:52
-
-
Save revolunet/cfc6fe0c5992897b29388373a8e51be7 to your computer and use it in GitHub Desktop.
Load remote components at run-time with script.js
This file contains 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 logo from './logo.svg'; | |
import './App.css'; | |
// https://github.com/ded/script.js | |
var $script = require("scriptjs"); | |
// load remote component and return it when ready | |
// display current children while loading | |
class LoadRemoteComponent extends Component { | |
state = { | |
Component: null, | |
error: null | |
} | |
componentDidMount() { | |
// expose React for UMD build | |
window.React = React; | |
// async load of remote UMD component | |
$script(this.props.url, () => { | |
let target = window[this.props.name]; | |
if (target) { | |
// loaded OK | |
this.setState({ | |
error: null, | |
Component: target | |
}) | |
} else { | |
// loaded fail | |
this.setState({ | |
error: `Cannot load component at ${this.props.url}`, | |
Component: null | |
}) | |
} | |
}); | |
} | |
render() { | |
if (this.state.Component) { | |
return <this.state.Component {...this.props.props} /> | |
} else if (this.state.error) { | |
return <p>{ this.state.error }</p> | |
} else { | |
return this.props.children | |
} | |
} | |
} | |
// props for the component when ready | |
const SAMPLE_PROPS = { | |
json: [{ | |
task: "Learn React", | |
done: true | |
},{ | |
task:"Write Book", | |
done: false | |
}] | |
}; | |
class App extends Component { | |
render() { | |
return ( | |
<div className="App"> | |
<div className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<h2>Welcome to React</h2> | |
</div> | |
<LoadRemoteComponent url="https://npmcdn.com/[email protected]" name="ReactJSONViewer" props={ SAMPLE_PROPS }> | |
<p>Loading remote bundle...</p> | |
</LoadRemoteComponent> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, Can I use script js in index.html file of my react app?
Thank you.
Irfan