简体   繁体   中英

How to load third party script and initialise class in React component

Working Implementation:

The following implementation in HTML file works. (Instructions from third party library)

<script src="https://cdn.somethirdpartyfile.js"></script>
<script>
  const client = new myThirdParyClass({
     param1: "test",
     param2: "test"
  });
</script>

Problem: Sandbox Link

I am using the below code to add a 3rd party library to my react code base.

index.html:

<script src="https://cdn.somethirdpartyfile.js"></script>

Component Code

  useEffect(() => {
    let script = document.createElement("script");
    script.onload = function () {
      const client = new myThirdParyClass({
        param1: "test",
        param2: "test"
      });
    };

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

But my react code throws an error saying myThirdParyClass is not defined. How can I initialize the third-party class in my React component?

What you can do here is create another component that returns the script. you want to do this dynamically because 3d party scripts change. essentially, as the article below says, load the script in the of your react page only when you need it.

Here what i found from a quick google search.

https://medium.com/better-programming/loading-third-party-scripts-dynamically-in-reactjs-458c41a7013d

can you try to add the src and add the script tag to the body in your component like this?

const script = document.createElement("script");
script.src = 'https://cdn.somethirdpartyfile.js'; // new line
script.onload = function () {
   const client = new myThirdParyClass({
    param1: "test",
    param2: "test"
    });
  };
document.body.appendChild(script); // new line

You don't need another script tag for it, just use the Persona object.

Of course, you will get Persona un-def because it loaded via script and not defined in the scope of the current module.

// eslint-disable-next-line
const client = new Persona.Client({
  templateId: "tmpl_FLYT5sonEPaDPmgGSSf8j1eD",
  environment: "sandbox",
  onComplete: (inquiryId) => {
    console.log(`Sending finished inquiry ${inquiryId} to backend`);
  }
});

export default function App() {
  useEffect(() => {
    client.open();
  }, []);

  return <div className="App"></div>;
}

https://codesandbox.io/s/practical-fast-ten4h-forked-ryxg0?file=/src/App.js:60-522

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM