How to Write a Google Maps React Component

1,448 阅读1分钟
原文链接: www.fullstackreact.com

Integrating React with external libraries like Google or Facebook APIs can be confusing and challenging. In this discussion, we’ll look at how to integrate the Google Maps API with React. In this post we’ll deal with lazily-loading the library through building complex nested components.

This post is not only about how to use Google Maps, but how to use 3rd party libraries in React generally and how to build up rich interactive components.

Table of Contents

In this post, we’ll look at how we to connect the Google API and build a Google Maps Component.

Before we can integrate with Google Maps, we’ll need to sign up at Google to get an API key.

You’re more than welcome to use our apiKey, but please use it lightly so Google doesn’t cut off our api access so it works for everyone.

Our apiKey is:

Loading a Google-based Component

In order to use Google within our components, we’ll need to handle two technical boundaries:

  1. Loading the Google API
  2. Handling access to the Google API within our components.

Our goal here is to create an independent component that can handle these two tasks for us. Let’s build a GoogleApiComponent to handle taking care of this for us (alternatively, we’ve wrapped this into an npm module ( google-maps-react). Feel free to grab this npm module and head to the next section).

With our key in hand, we’ll need to load up the Google API on our page. We can handle this in multiple ways, including directly including the