Rohit
Rohit

Reputation: 7161

How to load a JavaScript file and call a JS function in a react web app?

I am calling a JavaScript SDK and invoking it's function in following fashion in my HTML code and it is working fine as expected.

Here is the code

<!DOCTYPE html>

<head>
    <title>My Test App</title>

    <script src="scripts/abc.js"></script>
    <script src="scripts/xyz.js" onload="initXYZ('Param1')"></script>
</head>


</html>

Now, I want to call this same Javascript SDK from a react web page. I want to call the scripts and invoke the initXYZ('Param1') function.

So far, I am able to load the SDK, but I am not sure how to call the function as i did above. Here is the code I wrote in react app.

import React, {useEffect, useRef} from "react";
import "./App.css"

const App = () => {
  const instance = useRef(null);

  useEffect(() => {
    const settingsTag = document.createElement("script");
    settingsTag.src = "scripts/abc.js";
    instance.current.appendChild(settingsTag);

    const websdkTag = document.createElement("script");
    websdkTag.src = "scripts/xyz.js";
    instance.current.appendChild(websdkTag);

    

  }, []);
  return (
    <>
    <h1>My React app</h1>
    <div ref={instance} >
    </>
  );
  
};
export default App;

Can you please help me to understand how to invoke the function in above code. Also is there a better way to what I did here?

Upvotes: 0

Views: 1498

Answers (2)

Avani Bataviya
Avani Bataviya

Reputation: 770

you can use react-helmet to add any js file to page

Upvotes: 2

St&#233;phane de Luca
St&#233;phane de Luca

Reputation: 13573

This is what I do with my own SDK.

Simply creates as many classes as you have sections in your desired SDK. Embed all those sub SDKs into an object SDK that you reference from your app. See how it might look like:

Sdk.js

// From here, pretend the following is the content of your sdk.js

class SdkAbc {
  static shared // The singleton
  constructor() {

    // If already created, returned the singleton
    if (SdkAbc.shared) return SdkAbc.shared

    // Actually create the instance
    SdkAbc.shared = this

    // You might want to write your init code right below
    
  }

  version() { 
     return 1.3
  }
    
}

class SdkXyz {
   // Same as above
}

// You SDK singleton can host as many SDK sections as you need
const Sdk = {
   abc: new SdkAbc(),
   xyz: new SdkXyz(),
}

export default Sdk

App.js

    import React, {useEffect, useRef} from "react";
    import "./App.css"

import sdk from './sdk/sdk' // provided sdk.js is your sdk file located in /sdk folder



    const App = () => {
    
      return (
        <>
        <h1>My React app</h1>
        <div>Sdk Abc version: {Sdk.abc.version()} >
        </>
      );
      
    };
    export default App;

Upvotes: 2

Related Questions