I have two react application deployed as header and footer at some urls
header - 'someurl/header'
footer - 'someurl/footer'
I want to integrate this in a third application
I am able to integrate one of them at a time and both the react application is properly loaded but when i integrate both of them together only first application loads properly, second also renders but not as react component
Here is my code snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin>.
</script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<script async>
fetch('http://url/footer')
.then((response) => response.text())
.then(data => {
const node = document.createRange().createContextualFragment(data);
document.getElementById("footer-container").appendChild(node);
});
</script>
<script defer >
fetch('http://url/header')
.then((response) => response.text())
.then(data => {
const node = document.createRange().createContextualFragment(data);
document.getElementById("header-container").appendChild(node)
});
</script>
<div id="header-container"></div>
<div id="outer_div">outer content</div>
<div id="footer-container"></div>
Any help or hints is appreciated thanks in advance
After struggling i found solution, detailed explanation
Unfortunately it is not possible to run several create-react-app applications on the same document because the JavaScript bundles resulting from a create-react-app project is not without side-effects: The bundled WebPack runtime writes an object on the global scope, which prevents to load several such bundles.
Somehow loading the scripts of the second React app has a side effect and prevents the bootstrapping of the first React app!
It turns out that the WebPack runtime is the problem here. The WebPack runtime adds an object to the global scope which is used to lazy-load chunks. The default name for this object is webpackJsonp
The Solution The name of the webpackJsonp object can be configured in the WebPack config.
// webpack.config.dev.json
...
output: {
...
jsonpFunction: 'jsonpApp2'
}
I found solution from here https://medium.jonasbandi.net/hosting-multiple-react-applications-on-the-same-document-c887df1a1fcd
Note: jsonpFunction not available in webpack 5, here is alternative in webpack 5 - output.jsonpFunction -> output.chunkLoadingGlobal
Have a look at this
module.exports = {
//...
output: {
//...
chunkLoadingGlobal: 'myCustomFunc',
},
};