How To Use Google Maps In React With Zero Libraries

There are plenty of tutorials out there which outline how to use Google Maps with React. However, they all use custom libraries. Well-chosen libraries are not an issue, they are the bedrock what makes the open-source JavaScript community so great - but there are several reasons you may decide you do not want to use a custom library to use Google Maps within your React application. They may include:

  • the library is an overkill for your simple needs
  • the library over-abstracts the API making it unsuitable for your requirements
  • the library is unmaintained
  • you just want a challenge!

Thankfully, using the Google Maps JavaScript API in a React SPA is a piece of cake! In this post we will walk though creating a custom React component which we can re-use throughout our app to display Google Maps. For those looking for more advanced implementations, I'll be posting follow-ups on mounting custom components within maps and using the markerclusterer.js library for adding Clusters to the map.

How to use Google Maps with React using no custom libraries

Step 1: Assuming you have a React application already set up using create-react-app, you'll first need to register an API from the Google Developers dashboard and enable the Maps JavaScript API. Details on how to do this can be found here.

Step 2: Create a custom GoogleMap component with the following implementation:

// Map.tsx

import React, { Component } from 'react';
import { render } from 'react-dom';

class Map extends Component {
    constructor(props) {
        super(props);
        this.onScriptLoad = this.onScriptLoad.bind(this)
    }

    onScriptLoad() {
        const mapId = document.getElementById(this.props.id);
        const map = new window.google.maps.Map(mapId, this.props.options);
    }

    componentDidMount() {

        if (window.google) {
            this.onScriptLoad();
            return;
        }

        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`;
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);

        s.addEventListener('load', e => {
            this.onScriptLoad()
        })
    }

    render() {
        return (
            <div style={{ width: 100%, height: 100% }} id={this.props.id} />
        );
    }
}

export default GoogleMap

The component above executes when the component mounts via the componentDidMount() method. It first checks if the global window.google object exists. If it does, this means the Google Maps script has already been loaded - and so it proceeds to onScriptLoad(). This check is important because this component may be rendered multiple times in your React application across multiple screens - and the Google Maps script must be loaded only once.

If the window.google global object does not already exist, it is added to the DOM and loaded. This is the equivalent of adding the following code to the index.html file:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" />

Note: Remember to replace the above YOUR_API_KEY with your API key as defined in Step 1.

Step 3: You can now test this component by including it within another component in your React application. For purposes of simplicity, we can add the map to the default screen of the application by adding it to the render() function in App.tsx like so:

render() {
    return (
        <Map
            id="myMap"
            options={{
                center: { lat: 41.0082, lng: 28.9784 },
                zoom: 8
            }}
        />
    );
}

Provided you have set your API key, this will render the map. If the GoogleMap is used multiple times within the same application you will need to ensure that the id prop passed in to the component is unique.

⚡ Further inspiration

The approach outlined in this post makes it super easy to use Google Maps in your React apps with zero dependencies. This means you have full access to the Google Maps JavaScript API with no abstractions.

Those looking to go a step further can investigate using custom React components instead of the default InfoWindow to display information when a Marker is clicked. I'll be posting a tutorial on how to do this soon (I hope!).