Home > OS >  How do I access the object inside a script file within my own jsx file?
How do I access the object inside a script file within my own jsx file?

Time:11-25

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:

  1. Add the script in my html file
  2. Place the div in some React component
  3. Be able to reach the TheObjectThatINeedToAccessFromScript so I can call initialize on it within my jsx file. Eg trough an import 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.

  • Related