Author -  Sai gowtham

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>
    );
  }
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY