This page shows how to render multiple root in the same web page
For instance, when you want to integrate React component in another HTML application (php, ruby,…) with templating, you may render several roots.
This demo shows you how to render twice the same root.
You can also create two different root elements (See the build section) but for the simplicity of the demo, we don't.
<div id="react-foo"></div>
<div id="react-bar"></div>
function HelloComponent(props) {
// the useState hook that store in memory the name and takes as default the props.name
const [name, setName] = React.useState(props.name);
// a fragment with no props and two elements h1 and input
return React.createElement(
React.Fragment, // a fragment element with 2 sub elements
null, // no key props
React.createElement("h1", null, "Hello, ", name, "!"),
React.createElement("input", { placeholder:'Change my name', onChange: (e) => setName(e.target.value) })
);
}
// if you load the react element in a async script
window.addEventListener("load", function () {
/**
* Hello Foo
*/
// Make a react element from the React component function
let fooElement = React.createElement(HelloComponent, {name: "Foo"});
// In which html tag, the element should render
const fooContainer = document.getElementById("react-foo");
// render foo
ReactDOM.render(fooElement, fooContainer);
/**
* Hello Bar
*/
let barElement = React.createElement(HelloComponent, {name: "Bar"});
const barContainer = document.getElementById("react-bar");
ReactDOM.render(barElement , barContainer);
});
Note that if you export raw functions, they are not yet React Element, you need to make them React aware with CreateElement.
let barElement = React.createElement(Component1, props);
You may also not want to show the same component but to show other roots. 1)
This example shows you how to create two bundles with webpack with Commons chunk to share code (in this case the UI components)
The two apps (app1.js,app2.js) would render their own root.
module.exports = {
entry: {
vendor: ["@material-ui/styles"],
app1: "./src/app.1.js",
app2: "./src/app.2.js",
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity,
}),
]
}
let rollupExecutionConfiguration = {
input: {
'component-1': 'src/component-1.js',
'component-2': 'src/component-2.js'
},
// Don't include the following dependencies in the bundle
// https://rollupjs.org/tools/#peer-dependencies
external: ['react', 'react-dom'],
output: {
// name of the output, the name is the json key, not the name of the file
entryFileNames: 'build-[name].js',
format: 'umd',
dir: "dist/",
// Provide global variables to use in the UMD build for externalized deps
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
}
}