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

How to render JSX in HTML

In this tutorial, you will learn how to render JSX in HTML.

Video tutorial:

Include JS files

First, you need to include the required JS files. The required JS files are:

  1. React
  2. React DOM
  3. Babel

You can download all these files from cdnjs.com. Make sure to include the UMD version and not CJS.

  • CJS: Common JS
  • UMD: Universal Module Definition

You might like:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.10/babel.js"></script>

Render JSX

The following code will render the JSX code directly in HTML.

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

<script type="text/babel">

	function MyApp() {
		return (
			<h1>Hello JSX</h1>
		)
	}

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

Make sure to set the type of script tag as “text/babel”.

Render JSX from an external JS file

To render JSX from an external JS file, you first need to include the JS file with a script tag having type as “text/babel”.

<script type="text/babel" src="js/MyApp.js"></script>

Then your “js/MyApp.js” file will look like this.

// src/MyApp.js

function MyApp() {
	return (
		<h1>Hello JSX</h1>
	)
}

ReactDOM.createRoot(
	document.getElementById("app")
).render(<MyApp />)

Check out our more tutorials on React JS. If you face any problem in following this, kindly do let me know.