Skip to content

Repository files navigation

travis buildMIT-LicenseGitterOpen Source Helpers

React Places Autocomplete

A React component to build a customized UI for Google Maps Places Autocomplete

Demo

Live demo: kenny-hibino.github.io/react-places-autocomplete/

Features

  1. Enable you to easily build a customized autocomplete dropdown powered by Google Maps Places Library
  2. Utility functions to geocode and get latitude and longitude using Google Maps Geocoder API
  3. Pass through arbitrary props to the input element to integrate well with other libraries (e.g. Redux-Form)
  4. Mobile friendly UX
  5. WAI-ARIA compliant

Installation

To install the stable version

yarn add react-places-autocomplete

or

npm install react-places-autocomplete --save

React component is exported as a default export

importPlacesAutocompletefrom'react-places-autocomplete';

geocodeByAddress and geocodeByPlaceId utility functions are named exports

import{geocodeByAddress,geocodeByPlaceId}from'react-places-autocomplete';

Getting Started

To use this component, you are going to need to load Google Maps JavaScript API

Load the library in your project

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

Create your component

importReactfrom'react';importPlacesAutocomplete,{geocodeByAddress,getLatLng,}from'react-places-autocomplete';classSimpleFormextendsReact.Component{constructor(props){super(props);this.state={address: 'San Francisco, CA'};this.onChange=address=>this.setState({ address });}handleFormSubmit=event=>{event.preventDefault();geocodeByAddress(this.state.address).then(results=>getLatLng(results[0])).then(latLng=>console.log('Success',latLng)).catch(error=>console.error('Error',error));};render(){constinputProps={value: this.state.address,onChange: this.onChange,};return(<formonSubmit={this.handleFormSubmit}><PlacesAutocompleteinputProps={inputProps}/><buttontype="submit">Submit</button></form>);}}exportdefaultSimpleForm;

Props

PropTypeRequiredDescription
inputPropsobjectArbitrary props to input element, value and onChange are required keys
renderSuggestionfunctionFunctional react component to render dropdown list item
renderFooterfunctionFunctional react component to render footer at the bottom of the dropdown list
classNamesobjectPass CSS classes to rendered elements
stylesobjectPass CSS styles to rendered elements
onSelectfunctionEvent handler to handle user's select event
onEnterKeyDownfunctionEvent handler that gets called when user presses Enter key while input is focused
onErrorfunctionError handler function that gets called when Google Maps API responds with an error
optionsobjectOptions to Google Maps API (i.e. bounds, radius)
debouncenumberNumber of milliseconds to delay before making a call to Google Maps API
highlightFirstSuggestionbooleanIf set to true, first list item in the dropdown will be automatically highlighted
shouldFetchSuggestionsfunctionComponent will fetch suggestions from Google Maps API only when this function returns true

inputProps

Type: Object, Required: true

PlacesAutocomplete is a controlled component. Therefore, you MUST pass at least value and onChange callback to the input element.

You can pass arbitrary props to the input element thorough inputProps object (NOTE: className and style props for the input element should be passed through classNames.input and styles.input respectively).

constinputProps={
value,// `value` is required
onChange,// `onChange` is requiredonBlur: ()=>{console.log('blur!');},type: 'search',placeholder: 'Search Places...',autoFocus: true,};

renderSuggestion

Type: Functional React Component, Required: false

The function takes props with suggestion, formattedSuggestion keys (see the example below). We highly recommend that you create your own custom list item component and pass it as a prop.

/*********************************************** Example #1 List item example with `suggestion`************************************************/render(){constrenderSuggestion=({ suggestion })=>(<div><iclassName="fa fa-map-marker"/>{suggestion}</div>)return(<PlacesAutocompleteinputProps={inputProps}renderSuggestion={renderSuggestion}/>)}/*************************************************** Example #2 List item example with `formattedSuggestion`****************************************************/render(){constrenderSuggestion=({ formattedSuggestion })=>(<div><strong>{formattedSuggestion.mainText}</strong>{' '}<small>{formattedSuggestion.secondaryText}</small></div>)return(<PlacesAutocompleteinputProps={inputProps}renderSuggestion={renderSuggestion}/>)}

renderFooter

Type: Functional React Component Required: false

You can provide a component that will get rendered at the bottom of dropdown. For example, you can provide a component to show "Powered by Google" logo.

constrenderFooter=()=>(<divclassName="dropdown-footer"><div><imgsrc={require('./images/google-logo.png')}/></div></div>)// In render function<PlacesAutocompleteinputProps={inputProps}renderFooter={renderFooter}/>

classNames

Type: Object, Required: false

You can give a custom css classes to elements. Accepted keys are root, input, autocompleteContainer, autocompleteItem, autocompleteItemActive. If you pass classNames props, none of the default inline styles nor inline styles from styles prop will be applied to the element, and you will have full control over styling via CSS.

// classNames examplerender(){constcssClasses={root: 'form-group',input: 'form-control',autocompleteContainer: 'my-autocomplete-container'}return(<PlacesAutocompleteinputProps={inputProps}classNames={cssClasses}/>)}

Now you can easily apply custom CSS styles using the classNames!

styles

Type Object, Required: false

You can provide custom inline styles to elements. Accepted keys are root, input, autocompleteContainer, autocompleteItem, autocompleteItemActive.

constdefaultStyles={root: {position: 'relative',paddingBottom: '0px',},input: {display: 'inline-block',width: '100%',padding: '10px',},autocompleteContainer: {position: 'absolute',top: '100%',backgroundColor: 'white',border: '1px solid #555555',width: '100%',},autocompleteItem: {backgroundColor: '#ffffff',padding: '10px',color: '#555555',cursor: 'pointer',},autocompleteItemActive: {backgroundColor: '#fafafa',},};

Object passed via styles prop will be merged in with the above defaults and applied to their respective elements. NOTE: Passing classNames will disable any inline styling for respective elements.

// custom style examplesrender(){constmyStyles={root: {position: 'absolute'},input: {width: '100%'},autocompleteContainer: {backgroundColor: 'green'},autocompleteItem: {color: 'black'},autocompleteItemActive: {color: 'blue'}}return(<PlacesAutocompleteinputProps={inputProps}styles={myStyles}/>)}

onSelect

Type: Function Required: false, Default: null

You can pass a function that gets called instead of onChange function when user hits the Enter key or clicks on an autocomplete item.

The function takes three positional arguments. First argument is address, second is placeId, and the third is the place's name.

consthandleSelect=(address,placeId,name)=>{this.setState({ address, placeId, name })// You can do other things with address string or placeId. For example, geocode :)}// Pass this function via onSelect prop.<PlacesAutocompleteinputProps={inputProps}onSelect={this.handleSelect}/>

onEnterKeyDown

Type: Function Required: false Deafult: noop

You can pass a callback function that gets called when pressing down Enter key when no item in the dropdown is selected. The function takes one argument, the value in the input field.

consthandleEnter=(address)=>{geocodeByAddress(address).then(results=>{console.log('results',results)})}// Pass this function via onEnterKeyDown prop.<PlacesAutocompleteinputProps={inputProps}onEnterKeyDown={this.handleEnter}/>

onError

Type: Function Required: false

You can pass onError prop to customize the behavior when google.maps.places.PlacesServiceStatus is not OK (e.g., no predictions are found)

Function takes status (string) and clearSuggestions (function) as parameters

// Log error status and clear dropdown when Google Maps API returns an error.constonError=(status,clearSuggestions)=>{console.log('Google Maps API returned error with status: ',status)clearSuggestions()}// In render function<PlacesAutocompleteinputProps={inputProps}onError={onError}/>

options

Type: Object Required: false Default: {}

You can fine-tune the settings passed to the AutocompleteService class with options prop. This prop accepts an object following the same format as google.maps.places.AutocompletionRequest (except for input, which comes from the value of the input field).

// these options will bias the autocomplete predictions toward Sydney, Australia with a radius of 2000 meters,// and limit the results to addresses onlyconstoptions={location: newgoogle.maps.LatLng(-34,151),radius: 2000,types: ['address']}// In render function<PlacesAutocompleteinputProps={inputProps}options={options}/>

debounce

Type: Number Required: false Default: 200

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

highlightFirstSuggestion

Type: Boolean Required: false Default: false

If set to true, first suggestion in the dropdown will be automatically highlighted.

shouldFetchSuggestions

Type: Function Required: false Default: () => true

You can pass a function to tell when to fetch suggestions from Google Maps API. It takes an input { value } and should return a boolean.

// Only fetch suggestions when the input text is longer than 3 characters.constshouldFetchSuggestions=({ value })=>value.length>3// In render function<PlacesAutocompleteinputProps={inputProps}shouldFetchSuggestions={shouldFetchSuggestions}/>

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-places-autocomplete';// `results` is an entire payload from Google API.geocodeByAddress('Los Angeles, CA').then(results=>console.log(results)).catch(error=>console.error(error));

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-places-autocomplete';// `results` is an entire payload from Google API.geocodeByPlaceId('ChIJE9on3F3HwoAR9AhGJW_fL-I').then(results=>console.log(results)).catch(error=>console.error(error));

getLatLng API

/** * Returns a promise * @param {Object} result * @return {Promise} */getLatLng(result);

result

Type: Object Required: true

One of the element from results (returned from Google Maps Geocoder)

import{geocodeByAddress,getLatLng}from'react-places-autocomplete';geocodeByAddress('Tokyo, Japan').then(results=>getLatLng(results[0])).then(({ lat, lng })=>console.log('Successfully got latitude and longitude',{ lat, lng }));

Discussion

Join us on Gitter if you are interested in contributing!

License

MIT

About

A React component for Google Maps Places Autocomplete

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages