Loading external scripts in a react component

In this tutorial, we are going to learn about how to load external scripts in a react component.

Sometimes we need to work with external js libraries in such cases we need to insert a 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.

Loading script in a component

In this example, we are using the refs to access the component HTML element and adding the external script file.

App.js
import React,{Component} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
  componentDidMount() {
    const script = document.createElement("script");    script.async = true;    script.src = "https://some-scripturl.js";    this.div.appendChild(script);  }
  render() {
    return (
      <div className="App" ref={el => (this.div = el)}>        <h1>Hello react</h1>
        {/* Script is inserted here */}
      </div>
    );
  }
}

export default App;

Output:

script-component

Loading scripts in head or body

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

App.js
import React,{Component} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
  componentDidMount() {
    const script = document.createElement("script");
    script.async = true;
    script.src = "https://some-scripturl.js";
    //For head
    document.head.appendChild(script);
    // For body
    document.body.appendChild(script);  }
  render() {
    return (
      <div className="App">
        <h1>Hello react</h1>
      </div>
    );
  }
}