Google Maps + React
UPDATE: There is newer post about this that discusses using Google Maps and React with ES6. There is also now a public repo up on github that contains the version from the more recent article: https://github.com/Dacello/react-google-maps
What Google wants you to do
Simple example directly from the Google Maps API Tutorial:
What React Doesn’t want you to do
google.maps.event.addDomListener(window, 'load', initialize);
The window is not within the scope of this component. In Reactland, if you ever need to manipulate the DOM, it should be done inside a component, and to an element contained within said component. In this case we don’t really need to manipulate the DOM, the example is just doing that run the create map function after the page loads.
In React we can do this using
componentDidMount, which is called after the component has been rendered. We have to wait for the component to be rendered because Google requires you to manipulate the DOM, which is non existent before the component is rendered (or the page is loaded).
This is not ideal because it cancels out the performance advantage of React. The result is that most of the page loads nice and fast, but the map gets rendered slowly, since it has to wait for the component to render before hitting the google maps api to render the map.
The other non-reacty code which google suggests:
Google suggests that you get your DOM element via
document.getElementById('map_canvas'). Similarly to using
document is out of scope of this component. Another thing is that in Reactland, instead of using
document.getElementById, you are supposed to use Refs. Refs are easy. Just add
ref="map_canvas" to the element, and then then access it throughout the component with
GMap React Component
This is a very simplified version of a GMap component of ours. This assumes you only want one marker and one infoWindow, and you are passing in the coordinates to the component’s props. Notice the filetype is cjsx, which is JSX, just in CoffeeScript.