React component for easily use Google Places Autocomplete
First, load Google Maps JavaScript API:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY&libraries=places"></script>
Install the latest version:
npm install --save react-google-places-autocomplete
or
yarn add react-google-places-autocomplete
Use the component!
import React from 'react';
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';
// If you want to use the provided css
import 'react-google-places-autocomplete/dist/index.min.css';
const Component = () => (
<div>
<GooglePlacesAutocomplete
onSelect={console.log}
/>
</div>
);
export default Component;
Note:
- this is the simplest way to use the component.
- if you pass down the
apiKey
prop to the component, you can skip loading the Google Maps JavaScript API, as the component will inject that script on the page.
Prop | Type | Required | Default |
---|---|---|---|
apiKey | string | '' | |
autocompletionRequest | object | {} | |
debounce | number | 300 | |
disabled | boolean | false | |
idPrefix | string | '' | |
initialValue | string | '' | |
inputClassName | string | '' | |
inputStyle | object | {} | |
loader | node | null | |
onSelect | function | () => {} | |
displayFromSuggestionSelected | function | (suggestion) => ( suggestion.description ) |
|
placeholder | string | 'Address' | |
renderInput | function | undefined | |
renderSuggestions | function | undefined | |
required | boolean | false | |
suggestionsClassNames | shape | { container: '', suggestion: '', suggestionActive: '' } |
|
suggestionsStyles | shape | { container: {}, suggestion: {} } |
|
withSessionToken | boolean | false |
If this parameter is passed, the component will inject the google places script usign this APIKEY
.
Autocompletion request object to add restrictions to the search. Let's see the shape this prop can take:
autocompletionRequest = {
bounds: Array<LatLng>,
componentRestrictions: {
country: String | Array<String>
},
location: LatLng,
offset: Number,
radius: Number,
types: Array<String>,
}
Where:
LatLng
is an object like{ lat: Number, lng: Number }
.- bounds is an array of lenght 2, where the first value is the south west coordinate and the last one is the north east coordinate.
- country is one from ISO 3166-1 Alpha-2 country code. For example, 'us', 'ca', or 'uy'. You can provide a single one, or an array of up to five country code strings.
Examples:
...
<GooglePlacesAutocomplete
autocompletionRequest={{
bounds: [
{ lat: 50, lng: 50 },
{ lat: 100, lng: 100 }
],
}}
/>
...
...
<GooglePlacesAutocomplete
autocompletionRequest={{
componentRestrictions: {
country: ['us', 'ca', 'uy'],
}
}}
/>
...
Note: for more information check google documentation.
The number of milliseconds to delay before making a call to Google Maps API.
Initial value for the input.
Example:
...
<GooglePlacesAutocomplete
initialValue="Main St. 101"
/>
...
Custom className
for the input. Passing this prop will cause the input to ONLY use this className
and not the one
provided by the library.
Inline styles for the input.
Node to be shown when the component is calling to Google Maps API.
Example:
import loader from '../assets/loader.svg';
...
<GooglePlacesAutocomplete
loader={<img src={loader} />}
/>
...
Function to be called when the user selects one of the suggestions provided by Google Maps API.
Example:
...
<GooglePlacesAutocomplete
onSelect={({ description }) => (
this.setState({ address: description });
)}
/>
...
Function to be called when the user selects one of the suggestions provided by Google Maps API. The function receives a suggestion object as a parameter and returns a string to update the input value.
Example:
...
<GooglePlacesAutocomplete
displayFromSuggestionSelected={({ structured_formatting }) => (
structured_formatting.main_text
)}
/>
...
Placeholder for the input element.
Custom function for customizing the input.
Important: do not override the value
and onChange
properties of the input, neither the onBlur
or onKeyDown
.
Example:
...
<GooglePlacesAutocomplete
renderInput={(props) => (
<div className="custom-wrapper">
<input
// Custom properties
{...props}
/>
</div>
)}
/>
...
Custom function for customizing the suggestions list.
Example:
...
<GooglePlacesAutocomplete
renderSuggestions={(active, suggestions, onSelectSuggestion) => (
<div className="suggestions-container">
{
suggestions.map((suggestion) => (
<div
className="suggestion"
onClick={(event) => onSelectSuggestion(suggestion, event)}
>
{suggestion.description}
</div>
))
}
</div>
)}
/>
...
Custom classNames
for the different parts of the suggestions list.
Example:
{
container: 'custom-container-classname',
suggestion: 'custom-suggestion-classname',
suggestionActive: 'custom-suggestions-classname--active',
}
Passing this prop will cause the list to ONLY use this classNames and not the ones provided by the library.
Inline styles for the suggestions container and for each suggestion.
Example:
{
container: {
color: 'red',
},
suggestion: {
background: 'black',
},
}
Prefix for the id of the different tags on the component (input, suggestion container and suggestion row).
Exmaple:
idPrefix='left'
This is needed when you want to render more than one autocomplete input on the same page, in order to avoid the warning:
[DOM] Found 2 elements with non-unique id #google-places-autocomplete-input: (More info: https://goo.gl/9p2vKq)
If this prop is true
, the component will handle changing the sessionToken
on every session. To learn more about how this works refer to Google Places Session Token docs.
/**
* Returns a promise
* @param {String} address
* @return {Promise}
*/
geocodeByAddress(address);
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
import { geocodeByAddress } from 'react-google-places-autocomplete';
// `results` is an entire payload from Google API.
geocodeByAddress('Mohali, Punjab')
.then(results => console.log(results))
.catch(error => console.error(error));
Let's see the shape of results return by geocodeByAddress
results = [{
address_components:Array<Object>,
formatted_address: String,
geometry: {
bounds: LatLngBounds,
location: LatLng,
location_type: String,
viewport: LatLngBounds,
},
place_id: String,
types: Array<String>,
}]
/**
* Returns a promise
* @param {String} placeId
* @return {Promise}
*/
geocodeByPlaceId(placeId);
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
import { geocodeByPlaceId } from 'react-google-places-autocomplete';
// `results` is an entire payload from Google API.
geocodeByPlaceId('ChIJH_imbZDuDzkR2AjlbPGYKVE')
.then(results => console.log(results))
.catch(error => console.error(error));
Let's see the shape of results return by gecocodeByPlaceId
results = [{
address_components: Array<Object>,
formatted_address: String,
geometry: {
bounds: LatLngBounds,
location: LatLng,
location_type: String,
viewport: LatLngBounds,
},
place_id: String,
types: Array<String>,
}]
/**
* Returns a promise
* @param {Object} result
* @return {Promise}
*/
getLatLng(result);
Type: Object
Required: true
One of the elements from results
(returned from Google Maps Geocoder)
import { geocodeByAddress, getLatLng } from 'react-google-places-autocomplete';
geocodeByAddress('Mohali, Punjab')
.then(results => getLatLng(results[0]))
.then(({ lat, lng }) =>
console.log('Successfully got latitude and longitude', { lat, lng })
);
Let's see the shape of result return by getLatLng
result = {
lat: Number,
lng: Number,
}