Skip to content

Instantly share code, notes, and snippets.

@AbhiAgarwal192
Created April 18, 2021 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AbhiAgarwal192/2f34b37b431a89e79e923ff613b473a0 to your computer and use it in GitHub Desktop.
Save AbhiAgarwal192/2f34b37b431a89e79e923ff613b473a0 to your computer and use it in GitHub Desktop.
import React, {Component} from 'react';
class MicrofrontEnd extends Component {
componentDidMount() {
const { host, name, document } = this.props;
const scriptId = `micro-frontend-script-${name}`;
if (document.getElementById(scriptId)) {
console.log("renderMF");
this.renderMicroFrontend();
return;
}
fetch(`${host}/asset-manifest.json`)
.then((res) => res.json())
.then((manifest) => {
const script = document.createElement("script");
script.id = scriptId;
script.crossOrigin = "";
script.src = `${host}${manifest.files["main.js"]}`;
script.onload = () => {
this.renderMicroFrontend();
};
document.head.appendChild(script);
});
}
componentWillUnmount() {
const { name, window } = this.props;
window[`unmount${name}`](`${name}-container`);
}
renderMicroFrontend = () => {
const { name, window } = this.props;
window[`render${name}`](`${name}-container`);
};
render() {
return <main id={`${this.props.name}-container`} />;
}
}
MicrofrontEnd.defaultProps = {
document,
window,
};
export default MicrofrontEnd;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment