Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to load .js src from script tag in ReactJS

Getting Started with ReactJS

ReactJS, often simply known as React, is an open-source JavaScript library that was developed by Facebook to build dynamic user interfaces. It's an essential tool for any web developer's toolkit, and understanding how it works can significantly boost your coding efficiency.

In this post, we will discuss how to load JavaScript (.js) source files from a script tag in React. The script tag is a piece of HTML that allows you to embed external JavaScript files into your webpage.

What is a .js File?

Before moving forward, let's understand what a .js file is. A .js file is a standard JavaScript file. The .js extension signifies that the file contains JavaScript code. These files are used to run JavaScript on a webpage or a server (in the case of Node.js) and can be referenced in HTML using the <script> tag.

Importing .js Files in Traditional JavaScript

In traditional JavaScript, if you were to include a .js file, you would do so using the <script> tag in your HTML file. For example:

<script src="myJavaScriptFile.js"></script>

In the above line of code, src is an attribute that specifies the path to the JavaScript file that is to be included in the HTML file. The browser then fetches this file and executes it.

Importing .js Files in ReactJS

React, however, works a little differently. It doesn't interact with the HTML file directly in the same way. Instead, it uses a virtual DOM (Document Object Model) to interact with the webpage. The DOM can be thought of as a tree-like structure that represents the HTML of a webpage. React creates a virtual copy of this tree and uses it to decide what changes to make to the actual DOM to make it as efficient as possible.

Because of this, the traditional method of including a script tag in the HTML doesn't work in React. Instead, we use the import statement to include JavaScript files in React. For example:

import myJavaScriptFile from './myJavaScriptFile.js';

In this line of code, myJavaScriptFile is a variable that will hold the default export of myJavaScriptFile.js. The from keyword is followed by the path to the file.

Including External Scripts in ReactJS

But what if you want to include an external script in your React application? For example, you might want to include a JavaScript library that isn't available as a React component or isn't suitable to be included as a module.

Loading External JavaScript Files in ReactJS

There are a few ways to include an external JavaScript file in your React application. One way is to include the <script> tag directly in the public/index.html file in your React project.

<script src="https://externalwebsite.com/externalFile.js"></script>

This approach has the advantage of simplicity, but it also has some downsides. One is that you're not taking advantage of React's modular structure. Another is that you're loading the script for the entire application, whether it's used on a particular page or not.

Using useEffect Hook to Load External .js Files

A more react-ish way to load an external script would be to use the useEffect hook in conjunction with the createElement method from the document object.

The useEffect hook in React is a function that takes two arguments: a function that contains the side-effectful code, and a list of dependencies. If one of the dependencies changes, the function will be run again.

Here's how you can use it:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = "https://externalwebsite.com/externalFile.js";
    script.async = true;

    document.body.appendChild(script);

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

  return (
    // JSX goes here
  );
}

In this code, we're creating a new script element, setting its src attribute to the URL of the external script, and adding it to the body of the document. The async attribute is set to true to indicate that the script should be executed asynchronously, as soon as it's available.

The function returned by useEffect is a cleanup function that removes the script from the body when the component unmounts.

Conclusion

Loading a .js src from a script tag in ReactJS can be a bit tricky due to its unique way of dealing with the DOM. Yet, by using native JavaScript methods alongside React's useEffect hook, you can effectively load external scripts into your application. This enables you to use third-party libraries and scripts, thus extending the functionality of your React applications.

Remember, while loading external scripts can be helpful, it's also important to use them judiciously to maintain the performance of your React application. Always consider alternatives like finding a similar npm package or creating a custom React component before resorting to loading an external script.

Happy coding!