1

i have this script tag which i have used in my react app :

 <script type="text/javascript" src="http://url" async>
  {
  "interval": "1h",
  "width": 425,
  "isTransparent": false,
  "height": 450,
  "symbol": "BINANCE:BTCUSDT",
  "showIntervalTabs": true,
  "locale": "en",
  "colorTheme": "light"
  }
  </script>

i have used it in react like this:

const useScript = (url) => {
  useEffect(() => {
    const script = document.createElement('script',{colorTheme: 'dark',interval: '1h'}, null);

    script.src = url;
    script.async = true;
    // script.setAttribute("colorTheme","dark");
    // script.setAttribute("interval","1h");

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};

export default useScript;

and i call it inside my component, but i can't set parameters like "interval": "1h" and it uses the default values.

how can i do that ?

Gray
  • 531
  • 1
  • 10
  • 28

2 Answers2

0

Since you're trying to change the content inside the script tag, maybe you could create a new object replacing only the values you want to change, and then pass it to innerHTML, like:

script.innerHtml = JSON.stringify(yourObjectWithParameters);

P.S.: I didn't test the code above, it's just an idea.

  • I'm a little confused with what you're trying to accomplish. All the times that I had to import an script, it is usually organized in functions that you can call and pass any parameters to the function. I've never seen parameters being passed as an object inside the script tags. | Doing a little bit of research, though, it seems that another way of passing parameters is inserting them as query parameters in the script source url. This link contains other interesting links inside it as references: https://stackoverflow.com/questions/5292372/how-to-pass-parameters-to-a-script-tag – T. R. G. Moraes Aug 30 '20 at 16:06
  • Here, they also mention some different ways of passing parameters: https://stackoverflow.com/questions/5774672/whats-the-simplest-script-tag-with-params | Maybe if you give more details on what this script does and when it is executed, it would help on finding a solution to the problem. – T. R. G. Moraes Aug 30 '20 at 16:06
0

There's a very elegant way of doing this which doesn't involve the window object, it also allows for multiple of the same React component on the page (i.e. it scopes the variables to the component being mounted).

First, define the variables on your <script> tag like so:

<script src="script.js" data-valueone="one" data-valuetwo="two">
</script>

Inside script.js you can then use:

const scriptTag = document.currentScript; // gets the script tag that initialized the code
const data = scriptTag.dataset; // a map of all the data attributes on the tag

So in this case, data will be:

{
  valueone: "one",
  valuetwo: "two"
}
Samuel
  • 2,331
  • 1
  • 22
  • 40