Darth Plagueris
Darth Plagueris

Reputation: 339

Load Google Maps in React App - 'map is assigned a value but never used'

I am trying to render a map on a page using React but the map never displays. In console I can see this warning and it seems that the variable is not called anywhere. I have seen common implementations like this work on tutorials but I dont understand why it's not rendering here.

This is my App component code:

import React, {Component} from 'react';
import './App.css';

class App extends Component {

  componentDidMount() {
      this.renderMap();
  }

  renderMap = () => {
      this.loadScript("https://maps.googleapis.com/maps/api/" +
        "js?key=AIzaSyC1FpwqY0kv0hxQYPtGnn54ag14jHUI6Ow&callback=initMap");
      window.initMap = this.initMap;
  };

  loadScript = (url) => {
      const index = window.document.getElementsByTagName("script")[0];
      const script = window.document.createElement("script");
      script.src = url;
      script.async = true;
      script.defer = true;
      index.parentNode.insertBefore(script, index);
  };

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

  render() {
      return (
          <div className="App">
              <h1>Google Maps in React App</h1>
              <div id="map"> </div>
          </div>
      );
  }
}

export default App;

This is the warning in console:

webpackHotDevClient.js:120 ./src/App.js
Line 26:  'map' is assigned a value but never used  no-unused-vars

I have loaded the script in the component dynamically. Can someone help me out? Thanks.

Upvotes: 1

Views: 946

Answers (1)

aquiseb
aquiseb

Reputation: 989

That just means that you defined the variable map, but don’t use it. This warning comes from eslint and not google maps. In initMap, you may just add return map

Additionnally, you can also disable this eslint rule in your eslint config as explained here

Upvotes: 3

Related Questions