Skip to content

Instantly share code, notes, and snippets.

@puttpotsawee
Created June 25, 2021 12:41
Show Gist options
  • Save puttpotsawee/feeb901ec2a6c08013395416be089b74 to your computer and use it in GitHub Desktop.
Save puttpotsawee/feeb901ec2a6c08013395416be089b74 to your computer and use it in GitHub Desktop.
Micro Frontend Component
import React, { useEffect } from "react";
function MicroFrontend({ name, host, history }) {
useEffect(() => {
const scriptId = `micro-frontend-script-${name}`;
const renderMicroFrontend = () => {
window[`render${name}`](`${name}-container`, history);
};
if (document.getElementById(scriptId)) {
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 = () => {
renderMicroFrontend();
};
document.head.appendChild(script);
});
return () => {
window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`);
};
});
return <main id={`${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