How to make external javascript file work in ReactJs?

In a React project, my public.html file looks like this:

<head>
    <link rel="stylesheet" href="some_stylesheet_file.css">
</head>
<body>
    <div id="root"></div>

    <script src="function.js"></script>
</body>

All the components of the project load inside the “root” div. The “function.js” file is an external javascript file from a theme.

In one of the React components, I have an input field:

<input type="text" name="userName" id="userName" />

Now, inside “componentDidMount()” of that component, if I write

console.log(document.getElementByID("userName"))

it shows the “userName” field correctly in the console. But if I do the same thing in the “function.js” file, the output is null, which indicates the external javascript file is not working properly. I am not sure how to make the external javascript file work so that I can use the properties of the theme. Can anyone help?

Answer

We use the DOM method to load external JS in our ReactJS app.

For example, https://api.mesibo.com/mesibo.js is an external JS library provided by mesibo, we load it as following

const externalJS = "https://api.mesibo.com/mesibo.js";
const script = document.createElement("script");
script.src = externalJS;
document.body.appendChild(script);