React components for google places API.
Installations
npm install react-google-autocomplete
Releases
Mutation observer check existence
Published on 24 Nov 2021
Add refreshToken method to the service autocomplete
Published on 01 Nov 2021
Add libraries prop
Published on 25 Oct 2021
Fix closing brackets for selector
Published on 26 Aug 2021
Fix TS wrong types for autocomplete service
Published on 23 Aug 2021
Add places services into usePlacesAutocompleteService and expose sessionToken to outside
Published on 02 Jun 2021
Developer
ErrorPro
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
18.9.0
NPM Version
8.19.1
Statistics
480 Stars
115 Commits
114 Forks
9 Watching
6 Branches
23 Contributors
Updated on 14 Nov 2024
Bundle Size
9.11 kB
Minified
2.91 kB
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
19,067,083
Last day
-7.3%
29,320
Compared to previous day
Last week
-0.9%
154,357
Compared to previous week
Last month
-6.6%
665,429
Compared to previous month
Last year
22.8%
7,244,298
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Peer Dependencies
1
The package provides 3 tools for working with google places services:
- ReactGoogleAutocomplete is a simple html input component that provides functionality of the google places widgets.
- usePlacesWidget is a react hook that provides the same functionality as
ReactGoogleAutocomplete
does but it does not create any dom elements. Instead, it gives you back a react ref which you can set to any input you want. - usePlacesAutocompleteService is a more complex react hook. It uses google places autocomplete service and it provides all the functionality to you as the returned value. In addition to that, you can set a
debounce
prop which will reduce the amount of requests users send to Google.
If you find this package helpful please give it a star because it hepls it grow and motivates us to build new features and support the old ones.
Install
npm i react-google-autocomplete --save
or
yarn add react-google-autocomplete
As of version 1.2.4, you can now pass an apiKey
prop to automatically load the Google maps scripts. The api key can be found in your google cloud console.. The places service hook requires both the Places API and Maps Javascript API to be enabled.
1<Autocomplete 2 apiKey={YOUR_GOOGLE_MAPS_API_KEY} 3 onPlaceSelected={(place) => console.log(place)} 4/> 5or 6const { ref } = usePlacesWidget({ 7 apiKey: YOUR_GOOGLE_MAPS_API_KEY, 8 onPlaceSelected: (place) => console.log(place) 9}) 10 11<AnyInput ref={ref} />
Alternatively if not passing the apiKey
prop, you can include google autocomplete link api in your app. Somewhere in index.html or somewhere else. More info here
1<script 2 type="text/javascript" 3 src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places" 4></script>
ReactGoogleAutocomplete
This is a simple react component for working with google autocomplete
1import Autocomplete from "react-google-autocomplete"; 2 3<Autocomplete 4 apiKey={YOUR_GOOGLE_MAPS_API_KEY} 5 onPlaceSelected={(place) => { 6 console.log(place); 7 }} 8/>;
Props
-
apiKey
: pass to automatically load the Google maps scripts. The api key can be found in your google cloud console. -
ref
: React ref to be assigned the underlying text input ref. -
onPlaceSelected: (place:
PlaceResult, inputRef,
autocompleteRef) => void
: The function gets invoked every time a user chooses location. -
options
: Google autocomplete options.options.types
: By default it uses (cities).options.fields
: By default it usesaddress_components
,geometry.location
,place_id
,formatted_address
.
-
inputAutocompleteValue
: Autocomplete value to be set to the underlying input. -
googleMapsScriptBaseUrl
: Provide custom google maps url. By defaulthttps://maps.googleapis.com/maps/api/js
-
defaultValue
prop is used for setting up the default value e.gdefaultValue={'Amsterdam'}
. -
language
: Set language to be used for the results. If not specified, Google defaults to load the most appropriate language based on the users location or browser setting. -
libraries
: prop is used for loading additional google libraries alongside the places api,defaultValue={["places"]}
.
You can pass any prop specified for the hmtl input tag. You can also set options.fields prop if you need extra information, now it defaults to basic data in order to control expenses.
usePlacesWidget
Is a hook that has a single config argument. It has exactly the same interface as ReactGoogleAutocomplete props. This hook is actually used in the ReactGoogleAutocomplete component.
1import { usePlacesWidget } from "react-google-autocomplete"; 2 3export default () => { 4 const { ref, autocompleteRef } = usePlacesWidget({ 5 apiKey:YOUR_GOOGLE_MAPS_API_KEY, 6 onPlaceSelected: (place) => { 7 console.log(place); 8 } 9 }); 10 11 return <AnyInput ref={ref} {...anyOtherProp}> 12}
Arguments
It has only one config argument which has propperties: apiKey
, ref
, onPlaceSelected
, options
, inputAutocompleteValue
, googleMapsScriptBaseUrl
. The same props described here
Returned value
This hook returns object with only two properties:
ref
- is a react ref which you can assign to any input you would like.autocompleteRef
- is the autocomplete instance
usePlacesAutocompleteService
This is an initial implementation of debounced google places autocomplete service. It gives you an option to reduce the amount of requests sent to google which reduce your costs. For the time being we decided to use lodash.debounce
to save time and in the later versions we might write our own implementation of debounce with hooks. Because it uses lodash we also decided to not put it into the index library file so it lives in its own file and could be only imported by it.
1import usePlacesService from "react-google-autocomplete/lib/usePlacesAutocompleteService"; 2 3export default () => { 4 const { 5 placesService, 6 placePredictions, 7 getPlacePredictions, 8 isPlacePredictionsLoading, 9 } = usePlacesService({ 10 apiKey: process.env.REACT_APP_GOOGLE, 11 }); 12 13 useEffect(() => { 14 // fetch place details for the first element in placePredictions array 15 if (placePredictions.length) 16 placesService?.getDetails( 17 { 18 placeId: placePredictions[0].place_id, 19 }, 20 (placeDetails) => savePlaceDetailsToState(placeDetails) 21 ); 22 }, [placePredictions]); 23 24 return ( 25 <> 26 <Input 27 placeholder="Debounce 500 ms" 28 onChange={(evt) => { 29 getPlacePredictions({ input: evt.target.value }); 30 }} 31 loading={isPlacePredictionsLoading} 32 /> 33 {placePredictions.map((item) => renderItem(item))} 34 </> 35 ); 36};
Arguments
The hook has only one config argument.
config
:apiKey
: Google api key, otherwise google api has to be loaded manually.googleMapsScriptBaseUrl
: Provide custom google maps url. By defaulthttps://maps.googleapis.com/maps/api/js
.debounce
: Number of milliseconds to accumulate responses for.options
: Default options which will be passed to every request.sessionToken
: If true then a session token will be attached to every request.language
: If the language code is set, the results will be returned in the specificed languagelibraries
: prop is used for loading additional google libraries alongside the places api,defaultValue={["places"]}
.
Returned value
The hook returns an object with properties:
placesAutocompleteService
: Instance of AutocompleteServiceplacesService
: Instance of PlacesServiceautocompleteSessionToken
: Instance of AutocompleteSessionToken. You can use this to group several requests into a single sessionrefreshSessionToken
: call this function if you need to refresh the session tokenplacePredictions
: an array of AutocompletePredictionisPlacePredictionsLoading
: sets to true when agetPlacePredictions
request is being sent and not yet resolved.getPlacePredictions: (opt:
Options): void
: a function which you call whenever you want to request places predictions. Takes one argument.queryPredictions
: an array of QueryAutocompletePredictionisQueryPredictionsLoading
: sets to true whengetQueryPredictions
request is being sent and not yet resolved.getQueryPredictions: (opt:
Options): void
: a function which you call whenever you want to request query predictions. Takes one argument.
Examples
Simple autocomplete with options
1import Autocomplete from "react-google-autocomplete"; 2 3<Autocomplete 4 apiKey={YOUR_GOOGLE_MAPS_API_KEY} 5 style={{ width: "90%" }} 6 onPlaceSelected={(place) => { 7 console.log(place); 8 }} 9 options={{ 10 types: ["(regions)"], 11 componentRestrictions: { country: "ru" }, 12 }} 13 defaultValue="Amsterdam" 14/>;
or
1import { usePlacesWidget } from "react-google-autocomplete"; 2 3export default () => { 4 const { ref } = usePlacesWidget({ 5 apiKey: YOUR_GOOGLE_MAPS_API_KEY, 6 onPlaceSelected: (place) => { 7 console.log(place); 8 }, 9 options: { 10 types: ["(regions)"], 11 componentRestrictions: { country: "ru" }, 12 }, 13 }); 14 15 return <input ref={ref} style={{ width: "90%" }} defaultValue="Amsterdam" />; 16};
Getting access to the google autocomplete instance
1<Autocomplete 2 onPlaceSelected={(place, inputRef, autocomplete) => { 3 console.log(autocomplete); 4 }} 5/>
or
1const { ref, autocompleteRef } = usePlacesWidget({ 2 apiKey: YOUR_GOOGLE_MAPS_API_KEY, 3 onPlaceSelected: (place) => { 4 console.log(place); 5 }, 6});
More examples(dynamic props, MaterialUI, Ant, Bootstrap) could be found in docs/examples.js
Formik example lives here
Debounce example lives here
Typescript
We are planning on rewriting the library with TS/Flow in the later releases but you can already use it with TypeScript because we use declaration files.
TODO
Check that it fully works with SSRFully works with SSR: tested with: Next.js, Gatsby.js and custom SSR based on Express.js.- Add more UI libraries examples/supports
- Add eslint config(base-airbnb)
- Rewrite the lib to TS and add flow support
- Remove lodash and use own built-in solution for debouncing
Troubleshooting
- You have included the Google Maps JavaScript API multiple times on this page. Solution
Contribution
If you would like to see something in this library please create an issue and I will implement it as soon as possible.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29
- Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
- Info: no jobLevel write permissions found
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 1 commits out of 13 are checked with a SAST tool
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Warn: no linked content found
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
Found 11/28 approved changesets -- score normalized to 3
Reason
1 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 1
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-fhg7-m89q-25r3
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:42: update your workflow using https://app.stepsecurity.io/secureworkflow/ErrorPro/react-google-autocomplete/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:46: update your workflow using https://app.stepsecurity.io/secureworkflow/ErrorPro/react-google-autocomplete/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:57: update your workflow using https://app.stepsecurity.io/secureworkflow/ErrorPro/react-google-autocomplete/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:71: update your workflow using https://app.stepsecurity.io/secureworkflow/ErrorPro/react-google-autocomplete/codeql-analysis.yml/master?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Score
4.5
/10
Last Scanned on 2024-11-25
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 MoreOther packages similar to react-google-autocomplete
react-google-places-autocomplete
Google places autocomplete input for ReactJS.
react-native-google-places-autocomplete
Customizable Google Places autocomplete component for iOS and Android React-Native apps
react-places-autocomplete
A React component for Google Maps Places Autocomplete
use-places-autocomplete
React hook for Google Maps Places Autocomplete.