Incorporating a Script into Your NextJS Project using Typescript

I've been trying to insert a script from GameChanger () and they provided me with this code:

<!-- Place this div wherever you want the widget to be displayed -->
<div id="gc-scoreboard-widget-umpl"></div>

<!-- Insert this before the closing </body> tag -->
<script src="https://widgets.gc.com/static/js/sdk.v1.js"></script>
<script>
    window.GC.scoreboard.init({
        target: "#gc-scoreboard-widget-umpl",
        widgetId: "UUID HERE",
        maxVerticalGamesVisible: 4,
    })
</script>

Currently, I'm utilizing NextJS 14 with Typescript. Here is how my Component appears:

import Script from "next/script";

export default function GameChangerScoreboard() {
  return (
    <>
      <Script src="https://widgets.gc.com/static/js/sdk.v1.js" />
      <Script
        id="gc-scoreboard-init"
        dangerouslySetInnerHTML={{
          __html: `
                    window.GC.scoreboard.init({
                        target: 'gc-scoreboard-widget-umpl',
                        widgetId: "UUID HERE",
                        maxVerticalGamesVisible: 4
                    });
                `,
        }}
      />
      <div id="gc-scoreboard-widget-umpl"></div>
    </>
  );
}

When attempting this setup, I encountered the following error:

VM938:2 Uncaught TypeError: Cannot read properties of undefined (reading 'scoreboard')
    at <anonymous>:2:31
    at loadScript (script.js:140:19)
    at eval (script.js:223:17)
    // More error messages...

I'm uncertain about the cause of the error. Perhaps it's due to missing type information for the embed, but I'm not certain. Any assistance would be greatly appreciated.

Initially, I attempted a direct copy/paste of the code which didn't compile. Following CoPilot's suggestion, I used dangerouslySetInnerHTML which resulted in the current state of the code. I'm unsure of what my next steps should be.

Answer №1

This issue arises when the second script is executed before the window.GC object is defined. It seems likely that the first script creates this object, so it's important for the second script to run only after the initial one has finished loading and running. To achieve this, you can utilize the onLoad function within the NextJs Script component. By using this method, you can ensure that the second script executes only after the first script has been successfully loaded:

<Script
    src="https://widgets.gc.com/static/js/sdk.v1.js"
    onLoad={() => {
      window.GC.scoreboard.init({
        target: "#gc-scoreboard-widget-umpl",
        widgetId: "UUID HERE",
        maxVerticalGamesVisible: 4,
      });
    }}
/>

Another approach you could take is to implement a useEffect hook in your component. This hook will handle the initialization process only once the window.GC object is confirmed to exist, as shown below:

useEffect(() => {
    if (window.GC && window.GC.scoreboard) {
      window.GC.scoreboard.init({
        target: "#gc-scoreboard-widget-umpl",
        widgetId: "UUID HERE",
        maxVerticalGamesVisible: 4,
      });
    }
}, []);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any negatives to turning off create-react-app's SKIP_PREFLIGHT_CHECK option?

After setting up my create-react-app project, I added eslint as a dev dependency. My reasons for doing this include: 1) Running eslint as a pre-commit check using husky and lint-staged 2) Extending CRA's eslint with airbnb and prettier lint configs ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...

showcasing real-time webcam information within an HTML web application

I have successfully integrated my webcam data live into my web application using the following code snippet. The live feed from my webcam is now visible on the webpage. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta ...

Can the string literal type be implemented in an object interface?

My custom type is called Color, type Color = 'yellow' | 'red' | 'orange' In addition, I created an object with the interface named ColorSetting. interface ColorSetting { id: string yellow?: boolean red?: boolean orang ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

Exploring the intricacies of JSON object retrieval

I'm currently working on a form that allows users to submit address details for a selected location. However, before submitting the form, I want to give the user the ability to preview the address that will be sent. The addresses are stored within a J ...

My Ajax script is not recognizing the select tag value?

I am struggling with an ajax script that is supposed to send data from a contact form to a PHP script. The main issue I'm facing is that I can't seem to retrieve the value from the "select" tag. My knowledge of JavaScript/ajax is limited, so plea ...

Guide on how to conditionally render Container Classes

Initially, the designer provided me with this: Essentially, a category is passed from the previous screen. Through some UI interactions, I have to render this screen repeatedly. The flow goes like this: you choose a category, if it has subCategories, allo ...

Angular.js enables the ability to display views from several partials that are loaded dynamically

My goal is to create a view composed of multiple partials that are loaded dynamically based on the content type. While I am new to angular.js, my current approach in the controller involves: $(elem).html(string_with_src); $compile(elem.contents())($scope) ...

Is there a way for me to locate the ownerID?

I have a simple task that I need to complete My goal is for the user to be identified using my token when creating a post This is how the create function looks like: exports.create = async (req, res) => { const user = req.token; const users = awai ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

React transmits an incorrect argument through the function

Having a bit of trouble passing a parameter alongside the function in my for loop to create SVG paths. The props are working fine with the correct 'i' value except for selectRegion(i) which ends up getting the final value of 'i' after t ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

Can the CSS color of struts2-jquery-grid-tags be modified?

Is there a way to customize the CSS style of my Struts2 jQuery grid tags? I'm having trouble adjusting the font size of the header layer. Can someone please advise on how to change the style, color, and other formatting of the grid similar to regular ...

When making a GET request using Angular HttpClient, an error message stating "No overload matches this call" may

One issue I am facing is with a GET method in my backend. When sending a request body as input, I receive a list of results in return. However, the problem arises in my frontend: search(cat: Cat): Observable<Cat[]> { return this.httpClient.ge ...

Customizing the color of cells in an HTML table within a JSON based on their status

Would you like to learn how to customize the color of cells in an HTML table based on the status of a college semester's course map? The table represents all the necessary courses for your major, with green indicating completed courses, yellow for cou ...

Sharing Axios Response Data in VueJS: A Guide for Parent-Child Component Communication

Can someone please help me with using VueJS and Axios to retrieve API data and pass it to multiple child components? I am trying to avoid accessing the API multiple times in the child components by passing the data through props. The issue I am facing is ...