I am using React, and I am wondering how I can access the object that I have included as script
in my html
file within my own jsx
file
This is an example that I got:
<script src="url-to-some-script"></script>
<div id="an-id-wrapper">
<div id="an-id"></div>
</div>
<script>
var settings = { config: "some-config", id: "an-id" };
TheObjectThatINeedToAccessFromScript.initialize(settings);
</script>
I want to do something like:
- Add the script in my html file
- Place the div in some React component
- Be able to reach the
TheObjectThatINeedToAccessFromScript
so I can callinitialize
on it within myjsx
file. Eg trough animport TheObjectThatINeedToAccessFromScript from "some-where";
Please help me understand how I can do an import
on this script?
CodePudding user response:
It is now available on the window object, so I can access it trough there:
window.TheObjectThatINeedToAccessFromScript.initialize(settings);
CodePudding user response:
If I understand correctly, you just want to export
your initialize()
function from the script, and import it within your component. E.g:
function initialize() {
/*[...]*/
}
export { initialize };
import React, { useEffect } from 'react';
import { initialize } from './yourScriptFile';
/*[...]*/
function MyComponent() {
useEffect(() => {
initialize();
}, []);
return <div>{/*[...]*/}</div>
}
Unless it's absolutely vital, as a best practice, try to avoid binding things to the window. It can end in tears.