react-google-uni-autocomplete

React components for google autocomplete.

Usage no npm install needed!

<script type="module">
  import reactGoogleUniAutocomplete from 'https://cdn.skypack.dev/react-google-uni-autocomplete';
</script>

README

React google autocompletes

This is two react components for working with google autocomplete

Install

npm i react-google-autocomplete --save

You also have to include google autocomplete link api in your app. Somewhere in index.html or somwehrer else.

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"></script>

Example

Simple component out of box.

import {ReactGoogleAutocomplete} from 'react-google-autocomplete';

<ReactGoogleAutocomplete
    style={{width: '90%'}}
    onPlaceSelected={(place) => {
      console.log(place);
    }}
/>

The component has one function called onPlaceSelected. The function gets invoked every time a user chooses location.

Custom component

This component allows you point your own component as input, list's box, item. Here is example.

import {ReactCustomGoogleAutocomplete} from 'react-google-autocomplete';
//input itself
<ReactCustomGoogleAutocomplete
  {...fields.cityAutocomplete}
  input={<TextField/>}
  style={{width: '90%'}}
  initialValue={fields.location.value}
  onOpen={(list) => this.setState({list})}
  onClose={() => this.setState({list: null})}
/>
//dropdown container
<PopupContainer
  isOpened={this.state.list}
  onClose={() => {
    if (this.state.list) {
      this.setState({list: null});
    }
  }}
>
{this.state.list && this.state.list.map(item =>
  <FlatButton
    style={{width: '100%', textAlign: 'left'}}
    onClick={() => {
      console.log(item);
    }}
    label={item.description}
  />
)}
</ PopupContainer>

Props

  • input - <HTMLElement|Component> input which will be displayed.
  • initialValue - <place_id> if provided autocomplete will fetch the place from google and will update input's value as place.formatted_address.
  • onOpen - Function gets invoked every time input's value is changed.
  • onClose - Function get invoked every time input's value is empty.