Skip to content

Instantly share code, notes, and snippets.

@revolunet
Created September 16, 2016 14:52
Show Gist options
  • Save revolunet/cfc6fe0c5992897b29388373a8e51be7 to your computer and use it in GitHub Desktop.
Save revolunet/cfc6fe0c5992897b29388373a8e51be7 to your computer and use it in GitHub Desktop.
Load remote components at run-time with script.js
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/react-json-viewer@1.0.9" name="ReactJSONViewer" props={ SAMPLE_PROPS }>
<p>Loading remote bundle...</p>
</LoadRemoteComponent>
</div>
);
}
}
export default App;
@khanzzirfan
Copy link

Hi, Can I use script js in index.html file of my react app?

Thank you.
Irfan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment