React google maps

 

UPDATE: Glad to see people are still reading this article and asking questions. In order to provide a better working example, I went ahead and threw the example that was originally just on codepen into  a public repo on github: https://github.com/Dacello/react-google-maps. Feel free to fork, make a pull request, or just use this as an example. Thanks for reading, and please leave comments if you have any questions!


About a year ago, I wrote a blog post about using Google Maps with React. It gave a simple overview of how to write a React component that renders a map using the Google Maps API with a marker and an info window. The article also discussed a few things that Google encourages you to do in the tutorial which go against some general principles in React.

Ultimately, it concludes that Google Maps is usable with React, but we still have to rely on DOM manipulation in order to render the map, which doesn’t play nicely with React’s method of Reconciliation (the reason for React’s lightning fast rendering). Unfortunately, a year later, this is still the case. Even though that hasn’t changed, a lot of stuff has, namely the emergence of ES6. The purpose of this article is simply to give an up-to-date example of a React Google Maps component using ES6. So here it is:

see codepen

Notice that the older example of the GMap component in CoffeeScript is not too different from this version in ES6. Other than the differing syntax, let’s discuss some significant updates:

1. The use of let to assign variables. There is still a var, but let is generally what you want. See https://babeljs.io/docs/learn-es2015/#let-const

2. There is no longer a need for getInitialState. Now all we need is to define the state object on the component. To exemplify this, I went ahead and set up an initial state for updatedCenter and updatedZoom, which will get updated when the map is dragged or zoomed. The updated zoom and center get displayed above the map once they have been set.

3. Notice that we are no longer doing this.refs.mapCanvas.getDOMNode(), as it has been deprecated. Instead we just need to do this.refs.mapCanvas. Great! I never liked doing getDOMNode() anyway.

Now you have a simple example of a Google Maps React Component, this time in ES6. Keep your eyes peeled for a follow-up to this post, in which I’ll go dive a bit more in depth and discuss how to pass more map attributes into props, and have updates happen correctly using lifecycle hooks.

We're building an AI-powered Product Operations Cloud, leveraging AI in almost every aspect of the software delivery lifecycle. Want to test drive it with us? Join the ProdOps party at ProdOps.ai.