Marry Joanna
Marry Joanna

Reputation: 2803

Error adding Google Maps with react - TypeError: Cannot read property 'maps' of undefined

// App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Map from "./Map.js"


class App extends React.Component {



  constructor(props) {
    super(props);

    this.loadScript = this.loadScript.bind(this);
  }

  loadScript() {

    const API_KEY = process.env.REACT_APP_API_KEY;
    const url = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&libraries=places`;

    const s = document.createElement("script");
    s.src = url;
    document.head.appendChild(s);
  }

  componentWillMount() {

    this.loadScript();

  }


  render() {

    return (

      <div>

        <Map />


      </div>


    );

  }
}

export default App;

//Map.js

import React from "react"

export default class Map extends React.Component {

    constructor(props) {
        super(props);

        this.loadMap = this.loadMap.bind(this);
    }

    loadMap() {

        const map = new window.google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });
    }

    componentWillMount() {

        this.loadMap();
    }


    render() {


        return (


            <div id="map" style={{ width: 100, height: 100 }}></div>

        );

    }




}

Hi there, I am totally new to React, I am trying to load Google Maps without the help of a third-party library.

I have dynamically created a script tag and inserted it into the DOM. I am getting this error, trying to access the variables in the script.

My guess is that 'maps' is being accessed before the script is loaded. I am lost, on how to fix this error.

Upvotes: 1

Views: 332

Answers (1)

Anna Miroshnichenko
Anna Miroshnichenko

Reputation: 1213

When you load a script programmatically you can listen for "onload" event and do the rest of your logic when the script will be loaded. In this case, your loadScript function might look like this:

loadScript() {

  const API_KEY = process.env.REACT_APP_API_KEY;
  const url = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&libraries=places`;

  const s = document.createElement("script");
  s.src = url;
  document.head.appendChild(s);
  s.onload = function(e){
     console.info('googleapis was loaded');            
  }
}

You can add a scriptLoaded state to your App component and change it in the onload function, in this case, you need to render only if scriptLoaded is true :

  <div>
    {this.state.scriptLoaded && <Map />}
  </div>

Upvotes: 1

Related Questions