Last active
July 4, 2023 00:38
-
-
Save JenniferFuBook/0cd7d34548c76df1837988692880b54c to your computer and use it in GitHub Desktop.
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 from 'react'; | |
class MicroFrontend extends React.Component { | |
componentDidMount() { | |
const { name, host, document } = this.props; | |
const scriptId = `micro-frontend-script-${name}`; | |
if (document.getElementById(scriptId)) { | |
this.renderMicroFrontend(); | |
return; | |
} | |
fetch(`${host}/asset-manifest.json`) | |
.then(res => res.json()) | |
.then(manifest => { | |
const promises = Object.keys(manifest['files']) | |
.filter(key => key.endsWith('.js')) | |
.reduce((sum, key) => { | |
sum.push( | |
new Promise(resolve => { | |
const path = `${host}${manifest['files'][key]}`; | |
const script = document.createElement('script'); | |
if (key === 'main.js') { | |
script.id = scriptId; | |
} | |
script.onload = () => { | |
resolve(); | |
}; | |
script.src = path; | |
document.head.appendChild(script); | |
}) | |
); | |
return sum; | |
}, []); | |
Promise.allSettled(promises).then(() => { | |
renderMicroFrontend(); | |
}); | |
}); | |
} | |
componentWillUnmount() { | |
const { name, window } = this.props; | |
window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`); | |
} | |
renderMicroFrontend = () => { | |
const { name, window, history } = this.props; | |
window[`render${name}`] && | |
window[`render${name}`](`${name}-container`, history); | |
}; | |
render() { | |
return <main id={`${this.props.name}-container`} />; | |
} | |
} | |
MicroFrontend.defaultProps = { | |
document, | |
window | |
}; | |
export default MicroFrontend; |
is it possible to pass dynamic props from the host/container app to the microfrontend app?
is it possible to pass dynamic props from the host/container app to the microfrontend app?
We pass an object into the microfrontend app, which includes dynamic props to be used by child components. In turn, the microfrontend app can trigger changes for the container.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, it is a good suggestion. Thanks, @natansevero!