Include React JS component dynamically

In order to include a React JS component dynamically, we need to use the Javascript’s built-in fetch API. Let’s say you have a simple component that renders an <h1> tag:

// js/MyComponent.js

// create a simple component
function MyComponent() {
    return (
        <h1>My Component</h1>
    );
}

// render component
ReactDOM.createRoot(
    document.getElementById("my-component")
).render(<MyComponent />);

And in your index.html, you have your main React JS app.

<div id="app"></div>

<script type="text/babel">
    function App() {
        return (
            <>
                <div id="my-component"></div>
            </>
        );
    }

    ReactDOM.createRoot(
        document.getElementById("app")
    ).render(<App />);
</script>

Now you want to render your React JS component “MyComponent” dynamically in div having id=”my-component”. First, you need to use the fetch API to get the content of MyComponent.js file.

<script>

    // fetch component file content
    fetch("js/MyComponent.js")
        .then(function (response) {

            console.log(response.text());

        });

</script>
  • fetch: Fetch is a built-in modern browser API that allows you to execute HTTP requests.
  • response.text(): It will return not an actual string, but a promise. We need to resolve it by again chaining it with then() function.

Now we need to resolve the promise to get the actual string from response.

response.text().then(function (text) {
    console.log(text);
});

If you check your browser console now, you will see the exact code you have in your React JS component file. But this code is in JSX format, we need to compile it to native Javascript code. We can do that using Babel library:

// compile babel code to native javascript
const transpiledCode = Babel.transform(text, {
    presets: ["env", "react"]
}).code;

console.log(transpiledCode);

If you see the browser console now, you will see the native Javascript code.

  • Babel.transform: This function is used to transform the code from one format to another. It takes the code that needs to be transformed as 1st argument and an object for other options as 2nd argument.
  • presets: It will be an array that tells the Babel how to transform this code.
  • env: This ensures to convert the code such that it supports the older environments of Javascript like ES5.
  • react: This will convert the JSX or React code into plain Javascript code.
  • .code: This property will return the transformed code as string.
Convert JSX or React to native JS
Convert JSX to JS

Now we just need to execute this to render our React JS component dynamically. So we will simply use the eval() function that takes Javascript code as input string and execute it.

eval(transpiledCode);

Here is the complete code to include the React JS component dynamically in your project.

js/MyComponent.js

// create a simple component
function MyComponent() {
    return (
        <h1>My Component</h1>
    );
}

// render component
ReactDOM.createRoot(
    document.getElementById("my-component")
).render(<MyComponent />);

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Include React JS component dynamically</title>

        <script src="js/react.development.js"></script>
        <script src="js/react-dom.development.js"></script>
        <script src="js/babel.min.js"></script>
    </head>

    <body>

        <div id="app"></div>

        <script type="text/babel">
            function App() {
                return (
                    <>

                        <div id="my-component"></div>

                    </>
                );
            }

            ReactDOM.createRoot(
                document.getElementById("app")
            ).render(<App />);
        </script>

        <script>
            
            // fetch component file content
            fetch("js/MyComponent.js")
                .then(function (response) {

                    // text content of file
                    // it is a promise, so we will execute it
                    response.text().then(function (text) {

                        console.log(text);
                        
                        // compile babel code to native javascript
                        const transpiledCode = Babel.transform(text, {
                            presets: ["env", "react"]
                        }).code;

                        console.log(transpiledCode);

                        // execute the code as javascript
                        eval(transpiledCode);

                    });

                });

        </script>

    </body>
</html>

Download