Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-geosuggest

ubilabs59.9kMITdeprecated2.14.1TypeScript support: definitely-typed

please see @ubilabs/react-geosuggest for new versions

A React autosuggest for the Google Maps Places API.

react, react-component, google, autosuggest, autocomplete, places

readme

React Geosuggest Build Status

A React autosuggest for the Google Maps Places API. You can also define your own suggests as defaults. Works with Preact, too.

Demo

Live demo: ubilabs.github.io/react-geosuggest

Installation

As this component uses the Google Maps Places API to get suggests, you must include the Google Maps Places API in the <head> of your HTML:

<!DOCTYPE html>
  <html>
  <head><script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&libraries=places"></script>
  </head>
  <body></body>
</html>

Visit the Google Developer Console to generate your API key. The API's that you have to enable in your Google API Manager Dashboard are Google Maps Geocoding API, Google Places API Web Service and Google Maps Javascript API.

The easiest way to use geosuggest is to install it from NPM and include it in your own React build process (using Webpack, Parcel, etc).

You can also use the standalone build by including dist/react-geosuggest.js in your page. If you use this, make sure you have already included React, and it is available as a global variable.

npm install react-geosuggest --save

Usage

The Geosuggest works out of the box by just including it. However, you can customize the behaviour with the properties noted below.

ES6:

import Geosuggest from 'react-geosuggest';

<Geosuggest />

ES5:

var Geosuggest = require('react-geosuggest').default;

<Geosuggest />

Properties

placeholder

Type: String Default: Search places

The input field will get this placeholder text.

initialValue

Type: String Default: ''

An initial value for the input, when you want to prefill the suggest.

id

Type: String Default: ''

Define an ID for the geosuggest. Needed when there are multiple instances on a page.

className

Type: String Default: ''

Add an additional class to the geosuggest container.

style

Type: Object Default: { 'input': {}, 'suggests': {}, 'suggestItem': {} }

Add an additional style to Geosuggest. This would support overriding/adding styles to the input suggestList and suggestItem.

inputClassName

Type: String Default: ''

Add an additional class to the input.

disabled

Type: Boolean Default: false

Defines whether the input is disabled.

location

Type: google.maps.LatLng Default: null

To get localized suggestions, define a location to bias the suggests.

radius

Type: Number Default: 0

The radius in meters defines the area around the location to use for biasing the suggests. It must be accompanied by a location parameter.

bounds

Type: LatLngBounds Default: null

The bounds to use for biasing the suggests. If this is set, location and radius are ignored.

country

Type: String or Array Default: null

Restricts predictions to the specified country (ISO 3166-1 Alpha-2 country code, case insensitive). E.g., us, br, au. You can provide a single one, or an array of up to 5 country code strings.

types

Type: Array Default: null

The types of predictions to be returned. Four types are supported: establishment for businesses, geocode for addresses, (regions) for administrative regions and (cities) for localities. If nothing is specified, all types are returned. Consult the Google Docs for up to date types.

fixtures

Type: Array Default: []

An array with fixtures (defaults). Each fixture has to be an object with a label key in it. Optionally provide a location, but the Geosuggest will geocode the label if no location is provided.

You can also add a className key to a fixture. This class will be applied to the fixture item.

maxFixtures

Type: Number Default: 10

Maximum number of fixtures to render.

placeDetailFields

Type: Array Default: null

By default Google returns all fields when getting place details which can impact billing. You can optionally pass an array of fields to include in place results to limit what is returned and potentially reduce billing impact. geometry will always be added as we depend on the location for the suggest selection.

googleMaps

Type: Object Default: google.maps

In case you want to provide your own Google Maps object, pass it in as googleMaps. The default is the global google maps object.

ignoreTab

Type: Boolean Default: false

When the tab key is pressed, the onSelect handler is invoked. Set to true to not invoke onSelect on tab press.

ignoreEnter

Type: Boolean Default: false

When the enter key is pressed, the onSelect handler is invoked. Set to true to not invoke onSelect on enter press.

queryDelay

Type: Number Default: 250

Sets the delay in milliseconds after typing before a request will be sent to find suggestions. Specify 0 if you wish to fetch suggestions after every keystroke.

minLength

Type: Number Default: 1

Sets a minimum length of characters before a request will be sent to find suggestions.

highlightMatch

Type: Boolean Default: true

Highlights matched text.

onFocus

Type: Function Default: function() {}

Gets triggered when the input field receives focus.

onBlur

Type: Function Default: function(value) {}

Gets triggered when input field loses focus.

onChange

Type: Function Default: function(value) {}

Gets triggered when input field changes the value.

onKeyDown

Type: Function Default: function(event) {}

Gets triggered when input field has a key pressed down. This event is triggered before onKeyPress.

onKeyPress

Type: Function Default: function(event) {}

Gets triggered when input field gets key press.

onSuggestSelect

Type: Function Default: function(suggest) {}

Gets triggered when a suggest got selected. Only parameter is an object with data of the selected suggest. This data is available:

  • label – Type String – The label name
  • placeId – Type String – If it is a preset, equals the label. Else it is the Google Maps placeID
  • location – Type Object – The location containing lat and lng
  • gmaps – Type ObjectOptional! The complete response when there was a Google Maps geocode necessary (e.g. no location provided for presets). Check the Google Maps Reference for more information on it’s structure.

onUpdateSuggests

Type: Function Default: function(suggests, activeSuggest) {}

Gets triggered when the suggest list changes. Arguments include the suggest list and the current activeSuggest. Useful if you want to render the list of suggests outside of react-geosuggest.

onActivateSuggest

Type: Function Default: function(suggest) {}

Gets triggered when a suggest is activated in the list. Only parameter is an object with data of the selected suggest. This data is available:

  • label – Type String – The label name
  • placeId – Type String – If it is a preset, equals the label. Else it is the Google Maps placeID

onSuggestNoResults

Type: Function Default: function(userInput) {}

Gets triggered when there are no suggest results found

getSuggestLabel

Type: Function Default: function(suggest) { return suggest.description; }

Used to generate a custom label for a suggest. Only parameter is a suggest (google.maps.places.AutocompletePrediction). Check the Google Maps Reference for more information on it’s structure.

renderSuggestItem

Type: Function Default: null

Used to customize the inner html of SuggestItem and allows for controlling what properties of the suggest object you want to render. Also a convenient way to add additional styling to different rendered elements within SuggestItem. The function is passed both the suggestion and the user input.

skipSuggest

Type: Function Default: function(suggest) {}

If the function returns true then the suggest will not be included in the displayed results. Only parameter is an object with data of the selected suggest. (See above)

autoActivateFirstSuggest

Type: Boolean Default: false

Automatically activate the first suggestion as you type. If false, the exact term(s) in the input will be used when searching and may return a result not in the list of suggestions.

label

Type: String Default: null

If the label and a id prop (see "Others") were supplied, a <label> tag with the passed label text will be rendered. The <label> element's for attribute will correctly point to the id of the <input> element.

suggestsClassName

Type: String Default: ''

Add an additional class to suggest list.

suggestsHiddenClassName

Type: String Default: null

Additional className to toggle as the list of suggestions changes visibility.

suggestItemClassName

Type: String Default: ''

Add an additional class to suggest item.

suggestItemActiveClassName

Type: String, Default: null

Additional className to add when a suggestion item is active.

autoComplete

Type: String, Default: nope

Autocomplete input attribute.

inputType

Type: String, Default: text

The value for the type attribute on the html input element. Can be either text or search.

Others

All allowed attributes for input[type="text"] All DOM clipboard events. All DOM mouse events except for drag & drop. All data attributes.

Exposed component functions

These functions are accessible by setting "ref" on the component (see example below)

focus()

Call focus to focus on the element. The suggest list will be expanded with the current suggestions.

blur()

Call blur to blur (unfocus) the element. The suggest list will be closed.

update(value)

It is possible to update the value of the input contained within the GeoSuggest component by calling the update function with a new desired value of the type String.

clear()

It is also possible to clear the value of the input contained within the GeoSuggest component by calling the clear function.

selectSuggest()

Same effect as hitting enter (will geocode the text inside of the input).

Example

import React, {useRef} from 'react';
import ReactDOM from 'react-dom';
import Geosuggest from 'react-geosuggest';

const App = () => {
  const geosuggestEl = useRef(null);

  const fixtures = [
    {label: 'New York', location: {lat: 40.7033127, lng: -73.979681}},
    {label: 'Rio', location: {lat: -22.066452, lng: -42.9232368}},
    {label: 'Tokyo', location: {lat: 35.673343, lng: 139.710388}}
  ];

  /**
   * When a suggest got selected
   */
  const onSuggestSelect = (suggest) => console.log(suggest);

  return (
    <div>
      <Geosuggest
        ref={geosuggestEl}
        placeholder="Start typing!"
        initialValue="Hamburg"
        fixtures={fixtures}
        onSuggestSelect={onSuggestSelect}
        location={new google.maps.LatLng(53.558572, 9.9278215)}
        radius="20" />

      {* Buttons to trigger exposed component functions *}
      <button onClick={()=>geosuggestEl.current.focus()}>Focus</button>
      <button onClick={()=>geosuggestEl.current.update('New Zealand')}>Update</button>
      <button onClick={()=>geosuggestEl.current.clear()}>Clear</button>
      <button onClick={()=>geosuggestEl.current.selectSuggest()}>Search</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('app'));

Styling

This component uses BEM for namespacing the CSS classes. So styling should be easy and without conflicts. See the geosuggest.css for an example styling.

Note:

The geosuggest__suggests--hidden class is added to hide the suggestion list. You should copy the style below into your CSS file.

.geosuggest__suggests--hidden {
  max-height: 0;
  overflow: hidden;
  border-width: 0;
}

The above class is added whenever the suggestion list needs to be hidden. This occurs when the user selects an item from the list or when the user triggers the blur event on the input.

Similarly, you need to have the class geosuggest__item--active similar to this:

.geosuggest__item--active {
  background: #267dc0;
  color: #fff;
}

to see what item is selected, f.ex. when using the arrow keys to navigate the suggestion list.

Contributing

Issues and pull requests are welcome! Please read the guidelines in CONTRIBUTING.md before starting to work on a PR.

License

See LICENSE.md

changelog

2.14.1 (2021-01-28)

2.14.0 (2020-07-27)

Bug Fixes

  • geocode in selectSuggest when nothing selected (#470) (ada1de9f)

Features

  • add option for search input type (#471) (58264de2, closes #441)

2.13.1 (2020-06-19)

Bug Fixes

  • use secure URLs (#465) (86ec9227)
  • use a not random id for the list (#464) (68da464e)

2.13.0 (2020-05-08)

Bug Fixes

  • catch changing fixtures (#462) (3df1f8ee, closes #457)
  • stop bundling classnames and lodash.debounce (#458) (6ffbb4be)

Features

  • allow any data attributes (#460) (2d11ab9b)

2.12.1 (2019-10-30)

Bug Fixes

  • warning for componentWillMount (d8a661ec)
  • warnings for componentWillReceiveProps (b24117a1)
  • geosuggest: add a11y attributes to make suggestions be readable by screenreaders (b6b7f3dc)

2.12.0 (2019-04-08)

Features

  • use first suggest on selectSuggest when autoActivateFirstSuggest (#431) (6bc9850a, closes #423)

2.11.0 (2019-04-05)

Features

  • allow custom props for fixtures (82735c11)

2.10.0 (2019-01-18)

Bug Fixes

  • build: fix build on windows (#409) (15ff2569)
  • compatibility: change react and reactdom to peer dependencies (#410) (b4a8b40e, closes #405)

Features

  • geosuggest: add optional placeDetailsField prop to limit place details fields (#414) (ea820c4c)

2.9.0 (2018-10-19)

Features

  • geosuggest:
    • add Places API sessionToken support (issue #394) (3738916e)

2.8.0 (2018-06-21)

Bug Fixes

  • autoComplete prop default value: Change default value from off (which Chrome and other modern browsers ignore) to (462bd357)

Features

  • ignoreEnter: add new prop to disable enter key.. Rename current internal varaible named "igno (225eede4, closes #345)
  • Passes userInput to the renderSuggest function (f1eb98f)

2.7.0 (2017-12-11)

Features

  • SuggestItem: Adds hook to get list of suggests on when list changes (169951d)

2.6.0 (2017-11-10)

Bug Fixes

  • Geosuggest:
  • attributes: allow title (c8ce8d5b)
  • suggestions: Fixed erroneous check that hid the suggestions (5590955)

Features

2.5.0 (2017-08-17)

Features

  • filters: Add autoCapitalize and autoCorrect to filters (ff1153c2)

2.4.0 (2017-08-10)

Features

2.3.6 (2017-07-13)

Bug Fixes

  • Fix highlight label formatting (e652323)

2.3.5 (2017-07-11)

Bug Fixes

  • Fixed Geocoder not considering options (b1fd7c7)

2.3.4 (2017-06-26)

Bug Fixes

  • suggest-item: add missing key prop when rendering item (c88167e7)

2.3.3 (2017-06-19)

Bug Fixes

  • Use filter over find to fix IE11 compatibility (5dfff643)

2.3.2 (2017-06-19)

Bug Fixes

  • builds: fix build errors on Windows 10 (ab2cd25e)

2.3.1 (2017-06-16)

Bug Fixes

  • suggest-item:
    • highlight matches in fixtures, too (698ee71d)
    • correct highlight of matches not at index 0 (ac027a1d)

2.3.0 (2017-06-12)

Bug Fixes

  • check whether the label is an object to use the description value (1a5c2f78)
  • suggest-item: add missing key on iterated items (b9512063)

Features

  • Expose the onKeyDown event from input (80053d5)

2.2.0 (2017-06-09)

Bug Fixes

  • check for console before calling console.error (b6588bce)
  • allow for shift + arrow key behavior in input box ( 953d341)
  • suggest-item:
    • Items are not visible due to scroll when navigating using arrow keys (f471f96)
    • add renderSuggestItem prop for custom suggest item (f0ff0eb)

Features

2.1.0 (2017-01-11)

Bug Fixes

  • Do not use setState to save timer instance. (3709fdb6)

Features

  • changed to use reacts internal shallowCompare func (c66051d5)
  • add blur() (d16c61)
  • Added ARIA attributes to whitelist (5cb3f9a6)
  • label: add BEM class to geosuggest label (fb79f34e)
  • style:
    • allow custom hidden list class and active item class (57338753)
    • Allow adding custom classes to the suggest list and suggest item (ed69df6c)

2.0.1

Bug Fixes

  • refactor: changed to use reacts internal shallowCompare

2.0.0 (2016-10-07)

Bug Fixes

Features

  • Geosuggest: render label if id and label text where supplied (e2cbfc86)
  • prop-types: add label prop types (0345d63b)

1.25.1 (2016-09-23)

Bug Fixes

  • package: Specify addon as peer dependency (7be701c1)

Breaking Changes

  • react-addons-shallow-compare is now a peer dependency, meaning users must install it separately from react-geosuggest.

The peer dependency for react allows one to use either react 0.14 or 0.15. However, the dependency for react-addons-shallow-compare only allows 0.15 versions. For anyone using react 0.14 this causes warnings from npm saying that the peer dependency for react 0.15 (specified by react-addons-shallow-compare) is missing. This completely breaks workflows depending on npm shrinkwrap.

(7be701c1)

1.25.0 (2016-08-19)

Bug Fixes

  • Geosuggest: allow enter key events to propagate if suggestions are hidden (f993c6bc, closes #184)

Features

  • Geosuggest: pass on mouse and clipboard events (7dc64566, closes #182)
  • Geosuggest: Add a loading class on suggest loading (685812b7

1.24.1 (2016-06-21)

Bug Fixes

  • Geosuggest: fix server side rendering (428dedd8, closes #172)

1.24.0 (2016-06-21)

Bug Fixes

  • Geosuggest:
    • fix autoActivateFirstSuggest prop (f4409f7e)
    • Unset activeSuggest on blur and when not in suggestion list anymore (08ea143e)
    • Hide the suggest list when the result set is empty (6f23dc0e)
    • GeoCode fixtures if no location is provided (67ec4e5b)
    • Set autoComplete='off' and remove autoComplete option (33763dd9, closes #136)
    • initialise Google Maps in componentWillMount instead of componentDidMount (2f326427, closes #130)
  • example: add Google Maps API key (9c3c6d25, closes #107)
  • package:
    • add test cases and src/*.js to linter (61e3d08b)
    • add src/*.js to light-server watch list (68432ec1)

Features

  • on-blur: return current user input (e88eda42)
  • add support for inline styles (935fc71c)
  • Input obeys ignoreTab (5987f05b)
  • add queryDelay parameter (9daff3ac)
  • add onSuggestNoResults callback function (f51cacc0)

1.23.0 (2016-05-19)

Bug Fixes

  • Bug fix for IE 10, 'this' is not defined in the constructor function. We need to access the props directly from the argument. (2dca2727)

Features

  • Geosuggest: add onActivateSuggest event (ab2fc049)

1.22.0 (2016-04-26)

Features

  • Geosuggest:

1.21.0 (2016-04-15)

Features

1.20.1 (2016-04-06)

Bug Fixes

  • always add wrappers to input and suggests (91d1f4fb)

1.20.0 (2016-04-06)

Bug Fixes

  • example: switch to ES6 imports thanks to Babel bug (b5a066b8, closes #112)

Features

  • Add wrapper options and add them to example and README ( 4b9f9c7)

1.19.0 (2016-03-11)

Bug Fixes

  • remove isMounted antipattern (b347e9a3, closes #71)
  • Add className option for fixtures (880fe77)

Features

1.18.1 (2016-02-11)

Bug Fixes

  • input: use corrected list of allowed input attributes (d623c65c)
  • make classnames a real dependency (1fd93dd)

1.18.0 (2016-02-10)

Features

1.17.0 (2016-02-10)

Bug Fixes

  • Handle null value for Google suggestions (cfd84ad)

Features

  • add focus() to focus on the element (11c08af5)

1.16.1 (2016-02-07)

Bug Fixes

1.16.0 (2016-02-05)

Bug Fixes

  • autofocus -> autoFocus (7f9daa0)
  • use ignoreBlur flag to avoid hiding suggests when clicking one (4fa6bd2)
  • Escape user input for regex to avoid Exception (95b01ba)

Features

  • Use labelId instead of address to get the geocode (f95d2a3)

1.15.1 (2016-01-18)

Bug Fixes

1.15.0 (2016-01-18)

Features

  • allow all standard input type attributes (a43c388c, closes #80)

1.14.0 (2016-01-04)

Bug Fixes

  • check whether component is still mounted after timeout (67972d08, closes #71)
  • "use strict"; no longer throws errors if google cannot be loaded (d8c97c0)

Features

  • Add property for input class name. (c43b91a)

1.13.0 (2015-10-29)

Features

  • Remove defaults for search radius and location (17f0bf0)

1.12.0 (2015-10-22)

Bug Fixes

  • doc comments, backward compatible changes (96cca392)
  • add copy css in build module (bb988a1c)
  • googleMaps object moved out of props and set in componentDidMount (955812df)

1.11.1 (2015-10-12)

Bug Fixes

1.11.0 (2015-10-12)

Features

  • bump peer dependency react to 0.14.0 (dc39828e)
  • input: auto activate first suggest (d1429b86)

1.10.0 (2015-09-29)

Bug Fixes

  • prevent form submit on enter press (dda86a12, closes #49)

Features

  • add skipSuggest to not show certain suggestions (6da568d5
  • add getSuggestLabel to define a custom label (5103598
  • input: add disabled prop to disable (7100d43e

1.9.1 (2015-09-25)

Bug Fixes

  • Fix issue if the initialValue changes (b739b5c9)
  • Build fixes so dist/ works with a global window.React (9b5e4369)

1.9.0 (2015-09-09)

Features

  • input: add onChange callbacks (e6555ad

1.8.0 (2015-09-01)

Features

  • input: add method to change the value of the user input (44d86f5

1.7.0 (2015-08-19)

Features

  • suggests: add individual fixture classNames (01b0e8a

1.6.0 (2015-08-12)

Features

  • input: add bounds, country and types params (00a84866, closes #20)

1.5.0 (2015-08-12)

Features

  • input:

    • add clear method to geosuggest (2d38a40
    • add onFocus and onBlur callbacks (5051bc4
  • example: add onFocus and onBlur demo (88cf7f88)

1.4.3 (2015-07-29)

Bug Fixes

  • example: remove drop_console option from uglify (e8e16112)

1.4.2 (2015-07-29)

Bug Fixes

  • build: fix build for npm (6475372)

1.4.1 (2015-07-21)

Bug Fixes

1.4.0 (2015-07-20)

Bug Fixes

  • input: allow continuous editing (62e83cce, closes #12)

Features