0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Where to add this portion? Should I add this inside the React component?
We put it in index.html so that is available to all the components.
index.html is an html file. How can we write javascript there? Would you please explain exactly where should I add this portion and how I can integrate it to the index.html file?
use <script></script> tags in <head>
@JohnWink You could add inside useEffect for the component which needs it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.