This tutorial assumes you’ve already started developing your React app. If you need to build your app from scratch, refer to my step-by-step guide here.
If you’re new to React development like me, you’ve likely scoured the web for documentation on functional components. While it’s absolutely important to understand how class components translate into functional ones, continuously translating code is time-consuming and leaves room for error.
The npm package google-maps-react is no exception to outdated documentation. So I went through the pain of updating the class docs to functional components with hooks for you.
Step 1: Claim Your Google Maps API Key
Google has pretty good documentation on this, which you can access here.
An important thing to note is that Google requires your credit card information to verify your identity. They claim they will not charge you if you exceed your free API call max unless you enroll in automatic payments.
Step 2: Install Your Project Dependencies
Install the Google Maps React library: npm i google-maps-react
Step 3: Create a New Component
- Create a new component and populate with boilerplate using my fav VSCode shortcut “rfce” (react functional component export). In my example, I call this component “GoogleMap.js”.
- Import React and UseState from React and Map, Marker, GoogleAPIWrapper, and InfoWindow from google-maps-react.
- Pass props into your function and insert the Map component in your return statement, customizing zoom, style, and initialCenter attributes as needed.
- Define states for infoWindo, activeMarker, and selectedPlace, with the below default states.
- Add Marker and InfoWindow components inside of the Map component.
- Create onClick event handlers for when the user clicks on the map marker and map itself.
- Add the onClick handlers as attributes of the Map and Marker components.
Now, your exported component is ready to paste into the JSX in other components. You can see my GoogleMap component in Surf Break Costa Rica’s Intinerary here:
Like what you see? Check out SBCR’s GitHub repo to see how I incorporated Tailwind CSS to style the Itinerary page.
That’s a Wrap!
Oh, snap! I just showed you how to include a Google map in your React app!