Commit No Bug
Published on

Solving External Script Loading Problems in Modern React Applications

Authors
  • avatar
    Name
    nikUnique
    Twitter
React and external scripts

The Problem

I tried to use the Email Octopus inline subscription form in my Next.js website by placing an external script in my React component, and the form didn't appear anywhere. After some research, I found that you cannot just place an external script in your React component, but instead, one of the options is to use the useEffect hook, where you can create a script element and insert it into the body or some other place in the DOM. Below, I will show you the solution in code.

The Solution

First, I will show you the generic solution to the problem of not loading an external script in React from the Stack Overflow website. And then I will show my own version of the solution to my particular situation. The following code snippet is from the Stack Overflow website:

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

  script.src = "https://use.typekit.net/foobar.js";
  script.async = true;

  document.body.appendChild(script);

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

In the example above, the script was created and configured, and it was inserted into the body. But in my case, I added it programmatically from the useEffect hook into a specific div element within my JSX. Here is the code:

'use client'
import React, { useEffect, useRef } from 'react'

export default function SubscriptionForm() {
  const containerRef = useRef(null)

  useEffect(function () {
    if (!containerRef.current) return

    if (containerRef.current.children.length > 0) return

    const s = document.createElement('script')
    s.src = 'https://eocampaign1.com/form/[ACTUAL_ID].js'
    s.async = true
    s.setAttribute('data-form', '[ACTUAL_ID]')

    containerRef.current.appendChild(s)

    return () => containerRef?.current?.removeChild(s)
  }, [])

  return <div ref={containerRef}></div>
}

Here you go! This is the solution I used to the problem of not loading an external script in my application 😃.

Got questions? Send me an email to commitnobug@outlook.com