Skip to content

Instantly share code, notes, and snippets.

@bfunc
Last active September 9, 2018 08:05
Show Gist options
  • Save bfunc/17dd3afad8802aff7da738a8aec1486f to your computer and use it in GitHub Desktop.
Save bfunc/17dd3afad8802aff7da738a8aec1486f to your computer and use it in GitHub Desktop.
dynamic load and update ReactDOM tree (need localhost)
export default ({ host }) => {
let component;
return {
create: ({ DOMEelementId, type }) => {
console.log(`[${type}] resolving...`, DOMEelementId, type);
component && component.destroy();
const url = `${host}/modules/${type}.js`; // ExternalReactApp.js
import(url)
.then(module => {
console.log(`[${type}] resolved`);
component = module.default();
component.create({ DOMEelementId, initValue: 102 });
})
.catch(err => console.warn(err));
},
destroy() {
component && component.destroy();
component = undefined;
}
};
};
class MyCmp extends React.Component {
constructor(props) {
super(props);
this.state = { data: 2000 };
}
render() {
return React.createElement('div', null, [
React.createElement('div', {}, `Agent ${this.props.initValue} ${this.state.data} had arrived `),
]);
}
};
class ReactRootController {
constructor() { }
create({ DOMEelementId, initValue }) {
this.DOMEelementId = DOMEelementId;
console.log('this.DOMEelementId:', this.DOMEelementId);
this.react = ReactDOM.render(
React.createElement(MyCmp, { initValue }),
document.getElementById(this.DOMEelementId)
);
}
update(newParams) {
this.create({ ...params, ...newParams });
}
destroy() {
const element = document.getElementById(this.DOMEelementId);
element && ReactDOM.unmountComponentAtNode(element);
this.DOMEelementId = undefined;
}
}
export default (params) => {
return new ReactRootController(params)
};
<html>
<head>
<title><%= htmlWebpackPlugin.options.title %></title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="">
</head>
<body>
<!-- <script src="https://unpkg.com/[email protected]/umd/react.production.min.js" async></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" async></script> -->
<script src="https://unpkg.com/react@16/umd/react.development.js" async></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" async></script>
<script type="module">
const host = '<%= htmlWebpackPlugin.options.host %>/modules';
console.warn('[i]', host);
import(host + '/external-module.js')
.then(module => {
console.log('[external module] resolved');
window.ExternalModule = module.default({ host });
})
.catch(err => console.warn(err));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment