Rockstar5645
Rockstar5645

Reputation: 4518

React component failed to compile because 'google' is not defined (google charts)

I'm trying to use google charts and I keep on getting this error

Failed to compile.

src\Map.js
  Line 14:13:  'google' is not defined  no-undef       
  Line 17:13:  'google' is not defined  no-undef       
  Line 25:28:  'google' is not defined  no-undef       
  Line 42:29:  'google' is not defined  no-undef    

I was following this link here: https://developers.google.com/chart/interactive/docs/quick_start. Here is my Map.js file

import React, { useState, useEffect } from 'react';

function Map(props) {

    useEffect(() => {
        const script = document.createElement('script');
        script.src = "https://www.gstatic.com/charts/loader.js";
        script.async = true;
        script.setAttribute('id', 'gcs-5645')
        document.body.appendChild(script);
        
        document.getElementById('gcs-5645').addEventListener('load', () => {
            // Load the Visualization API and the corechart package.
            google.charts.load('current', {'packages':['corechart']});
        
            // Set a callback to run when the Google Visualization API is loaded.
            google.charts.setOnLoadCallback(drawChart);
        
            // Callback that creates and populates a data table,
            // instantiates the pie chart, passes in the data and
            // draws it.
            function drawChart() {
        
            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
            data.addRows([
                ['Mushrooms', 3],
                ['Onions', 1],
                ['Olives', 1],
                ['Zucchini', 1],
                ['Pepperoni', 2]
            ]);
        
            // Set chart options
            var options = {'title':'How Much Pizza I Ate Last Night',
                            'width':400,
                            'height':300};
        
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
            }; 
        }); 

    }, []); 

    return <div></div>; 
}

export default Map; 

I'm just trying to create a basic pie chart. It is my understanding that I have to wait until the script is loaded, and then the 'google' object will be globally accessible. But then why is it still not defined?

enter image description here

Am I thinking about this the right way? Is there a better way to do this?

Upvotes: 1

Views: 1086

Answers (1)

Rudrava Mukherjee
Rudrava Mukherjee

Reputation: 11

The issue if you were trying the dynamically adding scripts and adding onload listener it was loading the script but the google var was binded to window object so if you want to access you would have to use window.google.<functions> otherwise the output would be the one you got

The soulution as i had multiple components so i just set it as a state probably not a good idea but solves my purpose you can use the window.google object directly

CODE


index.html

<head>
    <script type="text/javascript" id="gc" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

</script>
</head>

app.js

export default function App() {
  const [gc, setGc] = useState(undefined);
  useEffect(() => {
    // this loads google charts
    setGc(window.google);
    console.log("googlecharts", gc);
  }, []);

The console output:

Upvotes: 0

Related Questions