Gathering detailed insights and metrics for react-places-autocomplete
Gathering detailed insights and metrics for react-places-autocomplete
Gathering detailed insights and metrics for react-places-autocomplete
Gathering detailed insights and metrics for react-places-autocomplete
@types/react-places-autocomplete
TypeScript definitions for react-places-autocomplete
react-google-autocomplete
React component for google autocomplete.
use-places-autocomplete
React hook for Google Maps Places Autocomplete.
react-google-places-autocomplete
Google places autocomplete input for ReactJS.
React component for Google Maps Places Autocomplete
npm install react-places-autocomplete
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,377 Stars
302 Commits
388 Forks
18 Watching
28 Branches
20 Contributors
Updated on 28 Oct 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-10.8%
26,734
Compared to previous day
Last week
-1.5%
133,770
Compared to previous week
Last month
8.6%
570,076
Compared to previous month
Last year
4.8%
7,931,680
Compared to previous year
2
1
36
In order to ensure active development going forward, we are looking for maintainers to join the project. Please contact the project owner if you are interested.
A React component to build a customized UI for Google Maps Places Autocomplete
Live demo: hibiken.github.io/react-places-autocomplete/
To install the stable version
1npm install --save react-places-autocomplete
React component is exported as a default export
1import PlacesAutocomplete from 'react-places-autocomplete';
utility functions are named exports
1import { 2 geocodeByAddress, 3 geocodeByPlaceId, 4 getLatLng, 5} from 'react-places-autocomplete';
To use this component, you are going to need to load Google Maps JavaScript API
Load the library in your project
1<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Create your component
1import React from 'react'; 2import PlacesAutocomplete, { 3 geocodeByAddress, 4 getLatLng, 5} from 'react-places-autocomplete'; 6 7class LocationSearchInput extends React.Component { 8 constructor(props) { 9 super(props); 10 this.state = { address: '' }; 11 } 12 13 handleChange = address => { 14 this.setState({ address }); 15 }; 16 17 handleSelect = address => { 18 geocodeByAddress(address) 19 .then(results => getLatLng(results[0])) 20 .then(latLng => console.log('Success', latLng)) 21 .catch(error => console.error('Error', error)); 22 }; 23 24 render() { 25 return ( 26 <PlacesAutocomplete 27 value={this.state.address} 28 onChange={this.handleChange} 29 onSelect={this.handleSelect} 30 > 31 {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => ( 32 <div> 33 <input 34 {...getInputProps({ 35 placeholder: 'Search Places ...', 36 className: 'location-search-input', 37 })} 38 /> 39 <div className="autocomplete-dropdown-container"> 40 {loading && <div>Loading...</div>} 41 {suggestions.map(suggestion => { 42 const className = suggestion.active 43 ? 'suggestion-item--active' 44 : 'suggestion-item'; 45 // inline style for demonstration purpose 46 const style = suggestion.active 47 ? { backgroundColor: '#fafafa', cursor: 'pointer' } 48 : { backgroundColor: '#ffffff', cursor: 'pointer' }; 49 return ( 50 <div 51 {...getSuggestionItemProps(suggestion, { 52 className, 53 style, 54 })} 55 > 56 <span>{suggestion.description}</span> 57 </div> 58 ); 59 })} 60 </div> 61 </div> 62 )} 63 </PlacesAutocomplete> 64 ); 65 } 66}
PlacesAutocomplete is a Controlled Component with a Render Prop. Therefore, you MUST pass at least value
and onChange
callback to the input element, and render function via children
.
Prop | Type | Required | Description |
---|---|---|---|
value | string | :white_check_mark: | value for the input element |
onChange | function | :white_check_mark: | onChange function for the input element |
children | function | :white_check_mark: | Render function to specify the rendering |
onSelect | function | Event handler to handle user's select event | |
onError | function | Error handler function that gets called when Google Maps API responds with an error | |
searchOptions | object | Options to Google Maps API (i.e. bounds, radius) | |
debounce | number | Number of milliseconds to delay before making a call to Google Maps API | |
highlightFirstSuggestion | boolean | If set to true , first list item in the dropdown will be automatically highlighted | |
shouldFetchSuggestions | boolean | Component will hit Google Maps API only if this flag is set true | |
googleCallbackName | string | You can provide a callback name to initialize PlacesAutocomplete after google script is loaded |
Type: string
,
Required: true
Type: function
,
Required: true
Typically this event handler will update value
state.
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={value => this.setState({ value })} 4> 5 {/* custom render function */} 6</PlacesAutocomplete>
Type: function
Required: true
This is where you render whatever you want to based on the state of PlacesAutocomplete
.
The function will take an object with the following keys.
getInputProps
: functiongetSuggestionItemProps
: functionloading
: booleansuggestions
: arraySimple example
1const renderFunc = ({ getInputProps, getSuggestionItemProps, suggestions }) => ( 2 <div className="autocomplete-root"> 3 <input {...getInputProps()} /> 4 <div className="autocomplete-dropdown-container"> 5 {loading && <div>Loading...</div>} 6 {suggestions.map(suggestion => ( 7 <div {...getSuggestionItemProps(suggestion)}> 8 <span>{suggestion.description}</span> 9 </div> 10 ))} 11 </div> 12 </div> 13); 14 15// In render function 16<PlacesAutocomplete value={this.state.value} onChange={this.handleChange}> 17 {renderFunc} 18</PlacesAutocomplete>;
This function will return the props that you can spread over the <input />
element.
You can optionally call the function with an object to pass other props to the input.
1// In render function
2<input {...getInputProps({ className: 'my-input', autoFocus: true })} />
This function will return the props that you can spread over each suggestion item in your
autocomplete dropdown. You MUST call it with suggestion
object as an argument, and optionally pass an object to pass other props to the element.
1// Simple example 2<div className="autocomplete-dropdown"> 3 {suggestions.map(suggestion => ( 4 <div {...getSuggestionItemProps(suggestion)}> 5 {suggestion.description} 6 </div> 7 ))} 8</div> 9 10// Pass options as a second argument 11<div className="autocomplete-dropdown"> 12 {suggestions.map(suggestion => { 13 const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item'; 14 return ( 15 <div {...getSuggestionItemProps(suggestion, { className })}> 16 {suggestion.description} 17 </div> 18 ); 19 })} 20</div>
This is a boolean flag indicating whether or not the request is pending, or has completed.
This is an array of suggestion objects each containing all the data from Google Maps API and other metadata.
An example of a suggestion object.
1{ 2 active: false, 3 description: "San Francisco, CA, USA", 4 formattedSuggestion: { mainText: "San Francisco", secondaryText: "CA, USA" }, 5 id: "1b9ea3c094d3ac23c9a3afa8cd4d8a41f05de50a", 6 index: 0, 7 matchedSubstrings: [ {length: 8, offset: 0} ], 8 placeId: "ChIJIQBpAG2ahYAR_6128GcTUEo", 9 terms: [ 10 { offset: 0, value: "San Francisco" }, 11 { offset: 15, value: "CA" }, 12 { offset: 19, value: "USA" } 13 ], 14 types: ["locality", "political", "geocode"] 15}
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 a suggestion item.
The function takes three positional arguments. First argument is address
, second is placeId
and third is the entire suggestion
object.
1// NOTE: `placeId` and `suggestion` are null when user hits Enter key with no suggestion item selected. 2const handleSelect = (address: string, placeId: ?string, suggestion: ?object) => { 3 // Do something with address and placeId and suggestion 4} 5 6// Pass this function via onSelect prop. 7<PlacesAutocomplete 8 value={this.state.value} 9 onChange={this.handleChange} 10 onSelect={this.handleSelect} 11> 12 {/* Custom render function */} 13</PlacesAutocomplete>
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
1// Log error status and clear dropdown when Google Maps API returns an error. 2const onError = (status, clearSuggestions) => { 3 console.log('Google Maps API returned error with status: ', status) 4 clearSuggestions() 5} 6 7<PlacesAutocomplete 8 value={this.state.value} 9 onChange={this.handleChange} 10 onError={onError} 11> 12 {/* Custom render function */} 13</PlacesAutocomplete>
Type: Object
Required: false
Default: {}
You can fine-tune the settings passed to the AutocompleteService class with searchOptions
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).
1// these options will bias the autocomplete predictions toward Sydney, Australia with a radius of 2000 meters, 2// and limit the results to addresses only 3const searchOptions = { 4 location: new google.maps.LatLng(-34, 151), 5 radius: 2000, 6 types: ['address'] 7} 8 9<PlacesAutocomplete 10 value={this.state.value} 11 onChange={this.handleChange} 12 searchOptions={searchOptions} 13> 14 {/* Custom render function */} 15</PlacesAutocomplete>
Type: number
Required: false
Default: 200
The number of milliseconds to delay before making a call to Google Maps API.
Type: boolean
Required: false
Default: false
If set to true
, first suggestion in the dropdown will be automatically set to be active.
Type: boolean
Required: false
Default: true
1// Only fetch suggestions when the input text is longer than 3 characters. 2<PlacesAutocomplete 3 value={this.state.address} 4 onChange={this.handleChange} 5 shouldFetchSuggestions={this.state.address.length > 3} 6> 7 {/* custom render function */} 8</PlacesAutocomplete>
Type: string
Required: false
Default: undefined
If provided, component will initialize after the browser has finished downloading google script.
IMPORTANT: To enable this async mode, you need to provide the same callback name to google script via callback=[YOUR CALLBACK NAME]
.
Example:
1<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=myCallbackFunc"></script>
Then, provide googleCallbackName
prop to PlacesAutocomplete
.
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={this.handleChange} 4 googleCallbackName="myCallbackFunc" 5> 6 {/* custom render function */} 7</PlacesAutocomplete>
NOTE: If there are more than one PlacesAutocomplete
components rendered in the page,
set up a callback function that calls a callback function for each component.
Example:
1<script> 2window.myCallbackFunc = function() { 3 window.initOne && window.initOne(); 4 window.initTwo && window.initTwo(); 5} 6</script> 7<script async defer 8src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=myCallbackFunc"></script>
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={this.handleChange} 4 googleCallbackName="initOne" 5> 6 {/* custom render function */} 7</PlacesAutocomplete> 8 9<PlacesAutocomplete 10 value={this.state.value} 11 onChange={this.handleChange} 12 googleCallbackName="initTwo" 13> 14 {/* custom render function */} 15</PlacesAutocomplete>
geocodeByAddress
API1/** 2 * Returns a promise 3 * @param {String} address 4 * @return {Promise} 5 */ 6geocodeByAddress(address);
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
1import { geocodeByAddress } from 'react-places-autocomplete'; 2 3// `results` is an entire payload from Google API. 4geocodeByAddress('Los Angeles, CA') 5 .then(results => console.log(results)) 6 .catch(error => console.error(error));
geocodeByPlaceId
API1/** 2 * Returns a promise 3 * @param {String} placeId 4 * @return {Promise} 5 */ 6geocodeByPlaceId(placeId);
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
1import { geocodeByPlaceId } from 'react-places-autocomplete'; 2 3// `results` is an entire payload from Google API. 4geocodeByPlaceId('ChIJE9on3F3HwoAR9AhGJW_fL-I') 5 .then(results => console.log(results)) 6 .catch(error => console.error(error));
getLatLng
API1/** 2 * Returns a promise 3 * @param {Object} result 4 * @return {Promise} 5 */ 6getLatLng(result);
Type: Object
Required: true
One of the element from results
(returned from Google Maps Geocoder)
1import { geocodeByAddress, getLatLng } from 'react-places-autocomplete'; 2 3geocodeByAddress('Tokyo, Japan') 4 .then(results => getLatLng(results[0])) 5 .then(({ lat, lng }) => 6 console.log('Successfully got latitude and longitude', { lat, lng }) 7 );
Join us on Gitter if you are interested in contributing!
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 10/13 approved changesets -- score normalized to 7
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
125 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More