New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-google-places-autocomplete

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-google-places-autocomplete

Google places autocomplete input for ReactJS.

  • 1.5.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
37K
decreased by-16.13%
Maintainers
1
Weekly downloads
 
Created
Source

React Google Places Autocomplete

React component for easily use Google Places Autocomplete

Getting started

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@latest

Use the component!

import React from 'react';
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';

const Component = () => (
  <div>
    <GooglePlacesAutocomplete
      onSelect={console.log}
    />
  </div>
);

export default Component;

Note: this is the simplest way to use the component.

Props

PropTypeRequiredDefault
autocompletionRequestobject{}
debouncenumber300
initialValuestring''
inputClassNamestring''
inputStyleobject{}
loadernodenull
onSelectfunction() => {}
placeholderstring'Address'
renderInputfunctionundefined
renderSuggestionsfunctionundefined
suggestionsClassNamesshape{ container: '', suggestion: '', suggestionActive: '' }
suggestionsStylesshape{ container: {}, suggestion: {} }
requiredbooleanfalse

autocompletionRequest

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.

debounce

The number of milliseconds to delay before making a call to Google Maps API.

initialValue

Initial value for the input.

Example:

...

  <GooglePlacesAutocomplete
    initialValue="Main St. 101"
  />

...

inputClassName

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.

inputStyle

Inline styles for the input.

loader

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} />}
  />

...

onSelect

Function to be called when the user select one of the suggestions provided by Google Maps API.

Example:

...

  <GooglePlacesAutocomplete
    onSelect={({ description }) => (
      this.setState({ address: description });
    )}
  />

...

placeholder

Placeholder for the input element.

renderInput

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>
    )}
  />

...

renderSuggestions

Custom function for customizing the suggestions list.

Example:

...

  <GooglePlacesAutocomplete
    renderSuggestions={(active, suggestions, onSelectSuggestion) => (
      <div className="suggestions-container">
        {
          suggestions.map((suggestion) => (
            <div className="suggestion">
              {suggestion.description}
            </div>
          ))
        }
      </div>
    )}
  />

...

suggestionsClassNames

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.

suggestionsStyles

Inline styles for the suggestions container and for each suggestion.

Example:

{
  container: {
    color: 'red',
  },
  suggestion: {
    background: 'black',
  },
}

Utility Functions

geocodeByAddress API

/**
 * Returns a promise
 * @param {String} address
 * @return {Promise}
 */
geocodeByAddress(address);
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>,
}]

geocodeByPlaceId API

/**
 * Returns a promise
 * @param {String} placeId
 * @return {Promise}
 */
geocodeByPlaceId(placeId);
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>,
}]

getLatLng API

/**
 * Returns a promise
 * @param {Object} result
 * @return {Promise}
 */
getLatLng(result);
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,
}

Keywords

FAQs

Package last updated on 06 Aug 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc