Using the Google Places Autocomplete JavaScript API in a React Application

Hamza Qaisarani
4 min readMar 29, 2018

--

I was in the process of creating a straight forward web application with React JS that would search for gyms in any given city. I also wanted to utilize the Google places autocomplete within the search functionality of the app, but I soon realized, as might many of you, that it was trickier than I first anticipated. So, I decided to write this quick article to show how I went about it.

Step One: Create React App

Before we get started, I’m going to assume you’ve already installed Node.js, and the create-react-app command.

After that, navigate to the directory where you want to store your application and then open up the terminal and use the create-react-app my-app-name command to set up your React application.

Step two: Installing Dependencies & Grabbing API key

First and foremost you’re going to need an API-Key for the Google Places API, which you can grab from here. Now, let’s get everything set up. All we’ll need to install is the react-load-script module with the following command.

$ npm install react-load-script --save

OPTIONAL: I’ll also be using another module for the input component, but it’s up to you if you choose to install this or not. A simple <input/> tag will suffice too.

$ npm install material-ui-search-bar --save

Once the installation is complete, your package.json file should look something like this

{
"name": "my-app", // your app name
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.1.1",
"material-ui-search-bar": "^0.4.1", // OPTIONAL
"react-load-script": "0.0.6" // use to load google maps library },
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
}
}

Step Three: Getting Down to Business

Part One:

Time to start coding now 😎. Let’s set up the foundation for the React component.

Part Two:

Now lets add the Script component that comes with the react-load-script module, into the render method.

return (
<div>
<Script url="https://maps.googleapis.com/maps/api/js? key=your_api_key&libraries=places"
onLoad={this.handleScriptLoad}
/>
<SearchBar
....
/>
</div>
);

The onLoad property takes in a function that is called once the library from the url attribute has been loaded. The handleScriptLoad method is where we’ll handle our google places autocomplete code.

handleScriptLoad() {   // Declare Options For Autocomplete 
const options = { types: [‘(cities)’] };

// Initialize Google Autocomplete
/*global google*/
this.autocomplete = new google.maps.places.Autocomplete(
document.getElementById(‘autocomplete’),
options );
// Avoid paying for data that you don't need by restricting the
// set of place fields that are returned to just the address
// components and formatted address
this.autocomplete.setFields(['address_components',
'formatted_address']);
// Fire Event when a suggested name is selected
this.autocomplete.addListener(‘place_changed’,
this.handlePlaceSelect);
}

In the handleScriptLoad method we start off by declaring the options for the autocomplete object. Feel free to dig into the docs for more options 🤓.

Then the autocomplete object is initialized with the id of the element that it is going to be attached to (in this case the SearchBar element).

The setField method allows us to limit the results produced by the autocomplete object. This aids in avoiding to pay for data that is not needed. You can read more about this within google’s documentations. Be sure to use setFields method to specify only the place data that you will use.

An event listener is then attached to the autocomplete object which listens for whenever a user selects one of the autocomplete suggestions. The handlePlacesSelected method is called when the event is triggered.

Part Three:

In the final part we’ll take care of updating the state when an autocomplete suggestion is selected. We’ll do this within the handlePlaceSelect method.

If you chose to install the material-ui-search-bar module, you’ll notice there’s a little bug in the <SearchBar /> component which causes the elements value to not update once an autocomplete suggestion is selected (as shown below)

Showing SearchBar Component Bug

To counter this, I used this.state.query to update the components value once a suggestion is selected.

And we’re done! The final result should look like this!

YAY! You did it! 😄
State variables should update as well!

UPDATE (2019):
If you wish to style the default autocomplete search results container, check out this link to get the CSS class selectors for the necessary components. Simple CSS should allow you to customize the autocomplete container to your hearts content.

ANOTHER UPDATE (2021):
If you’d like to utilize functional components and React hooks. I’ve written a quick example of how the <Search/> component would look like if it were written as a functional component.

If you enjoyed the article, feel free to give it a lil’claperino! 👏🏽

--

--