23 November 2019

This snippet shows you how you can use google places api in react to create address autocomplete dropdown. There are other service providers than google, but google supports business names in addresses as well. The easiest way to use the autocomplete is with two libraries, one for loading javascript and other that is the react component for the autocomplete dropdown. This method also supports debounce, to reduce the requests amount and save you money. Just set the debounce time, that is in milliseconds. Debounce is the time between keystrokes that will be waited before the request is sent, by default requests are made after each click. In this example I am using class names form Semantic UI, but you can customize it the way you want.

Source code viewer
  1. import React from 'react';
  2. import ReactDependentScript from 'react-dependent-script';
  3. import PlacesAutocomplete from 'react-places-autocomplete';
  4.  
  5. class AddressAutocompleteComponent extends React.PureComponent {
  6. constructor(props) {
  7. super(props);
  8. this.debounceTime = 450;
  9. this.initialState = {
  10. defect_address: '',
  11. };
  12.  
  13. this.defectAddressUpdate = this.defectAddressUpdate.bind(this);
  14. }
  15.  
  16. defectAddressUpdate(defect_address) {
  17. this.setState({ defect_address });
  18. }
  19.  
  20. render() {
  21. return <ReactDependentScript scripts={['https://maps.googleapis.com/maps/api/js?key=[KEY]&libraries=places']}>
  22. <PlacesAutocomplete
  23. value={this.state.defect_address}
  24. onChange={this.defectAddressUpdate}
  25. onSelect={this.defectAddressUpdate}
  26. debounce={this.debounceTime}>
  27. {({ getInputProps, suggestions, getSuggestionItemProps }) => (
  28. <div className="ui simple active fluid dropdown">
  29. <input {...getInputProps({className: 'search'})} />
  30. <div className="menu">
  31. {suggestions.map(suggestion => <div
  32. {...getSuggestionItemProps(suggestion, {className: suggestion.active ? 'selected item' : 'item'})}>
  33. {suggestion.description}
  34. </div>)}
  35. </div>
  36. </div>
  37. )}
  38. </PlacesAutocomplete>
  39. </ReactDependentScript>;
  40. }
  41.  
  42. }
Programming Language: ECMAScript