简体   繁体   中英

How do I use external script that I add to react JS?

I would like to add to my react component a

<script>http://xxx.xxx/XX.js</script>

I know I can simply add it using JSX, what I don't know is how to use it,

for instance this script has a function called A.Sort(), how can I call it and use it from a component?

You can load the script asynchronously and access it on load.

componentDidMount() {
  const script = document.createElement("script");
  script.src = "/static/libs/your_script.js";
  script.async = true;
  script.onload = () => this.scriptLoaded();

  document.body.appendChild(script);
}

It should get attached to the window .

 scriptLoaded() {
   window.A.sort();
 }

or

scriptLoaded() {
  A.sort();
}

You can include the tag in the /public/index.html, and then use the script as you use it in normal JS code, following example for if you want to use jQuery:

in your public/index.html include the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

And then anywhere you can use the jQuery functionality as usual:

window.$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

Sometimes we need to work with external js libraries in such cases we need to insert script tags into components, but in react we use jsx, so we can't add script tags directly just like how we add in HTML.

In this example, we will see how to load an external script file into a head, body elements, or component.

componentDidMount() {
    const script = document.createElement("script");
    script.async = true;
    script.src = "https://some-scripturl.js";
    script.onload = () => this.scriptLoaded();



    //For head
    document.head.appendChild(script);

    // For body
    document.body.appendChild(script);

    // For component
    this.div.appendChild(script);

  }

You can either modify your index.html file (if you are using one) by adding the required script.

Alternatively, if you can't edit it or you are not using it, there's a bunch of add-ons that solve this, for example react-load-script

You can use React Helmet npm

step 1 : npm i react-helmet

step 2 :

<Helmet>
    <script src="/path/to/resource.js" type="text/javascript" />
</Helmet>

After adding this script into your index.html

<script>http://xxx.xxx/XX.js</script>

you might check the available functions if you console.log(window) in App.js (or, wherever you want). Once you check the exact function, then you can use it like

window.A.sort();

I think this could be the simplest way. Just remember that you have to write 'window.' on the left side of your function.

A hooks version.

import * as React from "react";

function loadError(onError) {
  console.error(`Failed ${onError.target.src} didn't load correctly`);
}

function External() {
  React.useEffect(() => {
    const LoadExternalScript = () => {
      const externalScript = document.createElement("script");
      externalScript.onerror = loadError;
      externalScript.id = "external";
      externalScript.async = true;
      externalScript.type = "text/javascript";
      externalScript.setAttribute("crossorigin", "anonymous");
      document.body.appendChild(externalScript);
      externalScript.src = `https://externalurl.example.com/external.js?key=9393ABCDEFGH`;
    };
    LoadExternalScript();
  }, []);

  return <></>;
}

export default External;

If you want to import script in multiple components, then you can create your own custom hook that allows you to insert script in desired component:

import { useEffect } from 'react'
const importScript = src => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = src
    script.async = true
    document.body.appendChild(script)
    return () => {
      document.body.removeChild(script)
    }
  }, [src])
}
export default importScript

Using it on your desired component:

import importScript from 'import-path'
const DesiredComponent = props => {
  importScript("/path/to/resource")
  // ... rest of the code
}

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