How to inject multi React components in a page? A Multiple Root demo

About

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.

Demo

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.

  • The HTML with two div elements where we will render the same React component (called a root) with two different arguments:
    • respectively foo
    • and bar
<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) })
          );
}
  • The rendering
// 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);

});
  • Output

Building Multiple Roots

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);

Webpack

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,
     }),
    ]
  }

Rollup / Vite

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',
                },
            }
}





Discover More
React - App

A app is a react javascript that will render the root element when loaded. See ReactDOM rendering multiple root
React Render Element Splittsing
React - ReactDOM.render

ReactDOM.render is the main function that renders an element into a DOM element. It will be: the root element in a single page application or another react element called a secondary root, when...
React - Root element

The root element is the root element of the React DOM tree. It's the element passed to the rendering function ReactDOM.render where you will render your app or component. In a app, you have at minimal...



Share this page:
Follow us:
Task Runner