├── .babelrc
├── .github
└── workflows
│ └── codeql-analysis.yml
├── .gitignore
├── LICENSE.md
├── README.md
├── SECURITY.md
├── docs
├── debounce.js
├── example.gif
├── examples.js
└── formik.js
├── index.d.ts
├── index.js
├── lib
├── ReactGoogleAutocomplete.js
├── constants.js
├── index.js
├── usePlacesAutocompleteService.d.ts
├── usePlacesAutocompleteService.js
├── usePlacesService.js
├── usePlacesWidget.js
└── utils.js
├── package-lock.json
├── package.json
└── src
├── ReactGoogleAutocomplete.js
├── constants.js
├── index.js
├── usePlacesAutocompleteService.d.ts
├── usePlacesAutocompleteService.js
├── usePlacesWidget.js
└── utils.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "@babel/preset-react",
4 | [
5 | "@babel/preset-env",
6 | {
7 | "targets": {
8 | "ie": "11"
9 | }
10 | }
11 | ]
12 | // TODO: Minify breaks IE 11
13 | // ["minify"]
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ master ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ master ]
20 | schedule:
21 | - cron: '34 16 * * 4'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'javascript' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
37 | # Learn more:
38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
39 |
40 | steps:
41 | - name: Checkout repository
42 | uses: actions/checkout@v2
43 |
44 | # Initializes the CodeQL tools for scanning.
45 | - name: Initialize CodeQL
46 | uses: github/codeql-action/init@v1
47 | with:
48 | languages: ${{ matrix.language }}
49 | # If you wish to specify custom queries, you can do so here or in a config file.
50 | # By default, queries listed here will override any specified in a config file.
51 | # Prefix the list here with "+" to use these queries and those in the config file.
52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
53 |
54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
55 | # If this step fails, then you should remove it and run the build manually (see below)
56 | - name: Autobuild
57 | uses: github/codeql-action/autobuild@v1
58 |
59 | # ℹ️ Command-line programs to run using the OS shell.
60 | # 📚 https://git.io/JvXDl
61 |
62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
63 | # and modify them (or add more) to build your code if your project
64 | # uses a compiled language
65 |
66 | #- run: |
67 | # make bootstrap
68 | # make release
69 |
70 | - name: Perform CodeQL Analysis
71 | uses: github/codeql-action/analyze@v1
72 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .DS_Store
3 | /node_modules/
4 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Ven Korolev
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | 
4 | 
5 | 
6 | [](https://GitHub.com/ErrorPro/react-google-autocomplete/master/LICENSE)
7 |
8 | ## The package provides 3 tools for working with google places services:
9 |
10 | 1. [ReactGoogleAutocomplete](#reactgoogleautocomplete) is a simple html input component that provides functionality of the [google places widgets](https://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions).
11 | 2. [usePlacesWidget](#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.
12 | 3. [usePlacesAutocompleteService](#useplacesautocompleteservice) is a more complex react hook. It uses [google places autocomplete service](https://developers.google.com/maps/documentation/javascript/reference/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.
13 |
14 | 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.
15 |
16 | ## Install
17 |
18 | `npm i react-google-autocomplete --save`
19 |
20 | or
21 |
22 | `yarn add react-google-autocomplete`
23 |
24 |
25 |
26 | 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.](https://developers.google.com/maps/documentation/javascript/get-api-key). The places service hook requires both the Places API and Maps Javascript API to be enabled.
27 |
28 | ```js
29 | console.log(place)}
32 | />
33 | or
34 | const { ref } = usePlacesWidget({
35 | apiKey: YOUR_GOOGLE_MAPS_API_KEY,
36 | onPlaceSelected: (place) => console.log(place)
37 | })
38 |
39 |
40 | ```
41 |
42 | 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](https://developers.google.com/maps/documentation/places/web-service/autocomplete)
43 |
44 | ```html
45 |
49 | ```
50 |
51 | ## ReactGoogleAutocomplete
52 |
53 | This is a simple react component for working with google [autocomplete](https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete)
54 |
55 | ```js
56 | import Autocomplete from "react-google-autocomplete";
57 |
58 | {
61 | console.log(place);
62 | }}
63 | />;
64 | ```
65 |
66 | ### Props
67 |
68 | - `apiKey`: pass to automatically load the Google maps scripts. The api key can be found in your [google cloud console.](https://developers.google.com/maps/documentation/javascript/get-api-key)
69 |
70 | - `ref`: [React ref](https://reactjs.org/docs/hooks-reference.html#useref) to be assigned the underlying text input ref.
71 |
72 | - `onPlaceSelected: (place: `[PlaceResult](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlaceResult)`, inputRef, `[autocompleteRef](https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete)`) => void`: The function gets invoked every time a user chooses location.
73 |
74 | - `options`: [Google autocomplete options.](https://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions)
75 |
76 | - `options.types`: By default it uses (cities).
77 | - `options.fields`: By default it uses `address_components`, `geometry.location`, `place_id`, `formatted_address`.
78 |
79 | - `inputAutocompleteValue`: Autocomplete value to be set to the underlying input.
80 |
81 | - `googleMapsScriptBaseUrl`: Provide custom google maps url. By default `https://maps.googleapis.com/maps/api/js`
82 |
83 | - `defaultValue` prop is used for setting up the default value e.g `defaultValue={'Amsterdam'}`.
84 |
85 | - `language`: Set [language](https://developers.google.com/maps/documentation/places/web-service/details#PlaceDetailsRequests) 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.
86 |
87 | - `libraries`: prop is used for loading additional google libraries alongside the places api, `defaultValue={["places"]}`.
88 |
89 | You can pass any prop specified for the hmtl [input tag](https://www.w3schools.com/tags/tag_input.asp). You can also set [options.fields](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlaceResult) prop if you need extra information, now it defaults to basic data in order to control expenses.
90 |
91 | ## usePlacesWidget
92 |
93 | 
94 | 
95 |
96 | 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.
97 |
98 | ```js
99 | import { usePlacesWidget } from "react-google-autocomplete";
100 |
101 | export default () => {
102 | const { ref, autocompleteRef } = usePlacesWidget({
103 | apiKey:YOUR_GOOGLE_MAPS_API_KEY,
104 | onPlaceSelected: (place) => {
105 | console.log(place);
106 | }
107 | });
108 |
109 | return
110 | }
111 | ```
112 |
113 | ### Arguments
114 |
115 | It has only one config argument which has propperties: `apiKey`, `ref`, `onPlaceSelected`, `options`, `inputAutocompleteValue`, `googleMapsScriptBaseUrl`. The same props described [here](#reactgoogleautocomplete)
116 |
117 | ### Returned value
118 |
119 | This hook returns object with only two properties:
120 |
121 | - `ref` - is a react ref which you can assign to any input you would like.
122 | - `autocompleteRef` - is the [autocomplete](https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete) instance
123 |
124 | ## usePlacesAutocompleteService
125 |
126 | 
127 | 
128 |
129 | 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.
130 |
131 | ```js
132 | import usePlacesService from "react-google-autocomplete/lib/usePlacesAutocompleteService";
133 |
134 | export default () => {
135 | const {
136 | placesService,
137 | placePredictions,
138 | getPlacePredictions,
139 | isPlacePredictionsLoading,
140 | } = usePlacesService({
141 | apiKey: process.env.REACT_APP_GOOGLE,
142 | });
143 |
144 | useEffect(() => {
145 | // fetch place details for the first element in placePredictions array
146 | if (placePredictions.length)
147 | placesService?.getDetails(
148 | {
149 | placeId: placePredictions[0].place_id,
150 | },
151 | (placeDetails) => savePlaceDetailsToState(placeDetails)
152 | );
153 | }, [placePredictions]);
154 |
155 | return (
156 | <>
157 | {
160 | getPlacePredictions({ input: evt.target.value });
161 | }}
162 | loading={isPlacePredictionsLoading}
163 | />
164 | {placePredictions.map((item) => renderItem(item))}
165 | >
166 | );
167 | };
168 | ```
169 |
170 | [example](/docs/debounce.js)
171 |
172 | ### Arguments
173 |
174 | The hook has only one config argument.
175 |
176 | - `config`:
177 | - `apiKey`: Google api key, otherwise google api has to be loaded manually.
178 | - `googleMapsScriptBaseUrl`: Provide custom google maps url. By default `https://maps.googleapis.com/maps/api/js`.
179 | - `debounce`: Number of milliseconds to accumulate responses for.
180 | - `options`: Default [options](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#QueryAutocompletionRequest) which will be passed to every request.
181 | - `sessionToken`: If true then a [session token](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteSessionToken) will be attached to every request.
182 | - `language`: If the language code is set, the results will be returned in the specificed [language](https://developers.google.com/maps/documentation/places/web-service/details#PlaceDetailsRequests)
183 | - `libraries`: prop is used for loading additional google libraries alongside the places api, `defaultValue={["places"]}`.
184 |
185 | ### Returned value
186 |
187 | The hook returns an object with properties:
188 |
189 | - `placesAutocompleteService`: Instance of [AutocompleteService](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteService)
190 | - `placesService`: Instance of [PlacesService](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlacesService)
191 | - `autocompleteSessionToken`: Instance of [AutocompleteSessionToken](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteSessionToken). You can use this to [group several requests into a single session](https://developers.google.com/maps/documentation/places/web-service/session-tokens)
192 | - `refreshSessionToken`: call this function if you need [to refresh the session token](https://developers.google.com/maps/documentation/places/web-service/session-tokens)
193 | - `placePredictions`: an array of [AutocompletePrediction](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteResponse)
194 | - `isPlacePredictionsLoading`: sets to true when a `getPlacePredictions` request is being sent and not yet resolved.
195 | - `getPlacePredictions: (opt: `[Options](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompletionRequest)`): void`: a function which you call whenever you want to request places predictions. Takes one [argument](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompleteResponse).
196 | - `queryPredictions`: an array of [QueryAutocompletePrediction](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#QueryAutocompletePrediction)
197 | - `isQueryPredictionsLoading`: sets to true when `getQueryPredictions` request is being sent and not yet resolved.
198 | - `getQueryPredictions: (opt: `[Options](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#QueryAutocompletionRequest)`): void`: a function which you call whenever you want to request query predictions. Takes one [argument](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#QueryAutocompletionRequest).
199 |
200 | ## Examples
201 |
202 | ### Simple autocomplete with options
203 |
204 | ```js
205 | import Autocomplete from "react-google-autocomplete";
206 |
207 | {
211 | console.log(place);
212 | }}
213 | options={{
214 | types: ["(regions)"],
215 | componentRestrictions: { country: "ru" },
216 | }}
217 | defaultValue="Amsterdam"
218 | />;
219 | ```
220 |
221 | or
222 |
223 | ```js
224 | import { usePlacesWidget } from "react-google-autocomplete";
225 |
226 | export default () => {
227 | const { ref } = usePlacesWidget({
228 | apiKey: YOUR_GOOGLE_MAPS_API_KEY,
229 | onPlaceSelected: (place) => {
230 | console.log(place);
231 | },
232 | options: {
233 | types: ["(regions)"],
234 | componentRestrictions: { country: "ru" },
235 | },
236 | });
237 |
238 | return ;
239 | };
240 | ```
241 |
242 | ### Getting access to the google autocomplete instance
243 |
244 | ```js
245 | {
247 | console.log(autocomplete);
248 | }}
249 | />
250 | ```
251 |
252 | or
253 |
254 | ```js
255 | const { ref, autocompleteRef } = usePlacesWidget({
256 | apiKey: YOUR_GOOGLE_MAPS_API_KEY,
257 | onPlaceSelected: (place) => {
258 | console.log(place);
259 | },
260 | });
261 | ```
262 |
263 | ### More examples(dynamic props, MaterialUI, Ant, Bootstrap) could be found in [docs/examples.js](/docs/examples.js)
264 |
265 | Formik example lives [here](/docs/formik.js)
266 |
267 | Debounce example lives [here](/docs/debounce.js)
268 |
269 | ### Typescript
270 |
271 | 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](https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html).
272 |
273 | ### TODO
274 |
275 | - ~~Check that it fully works with SSR~~ Fully works with SSR: tested with: Next.js, Gatsby.js and custom SSR based on Express.js.
276 | - Add more UI libraries examples/supports
277 | - Add eslint config(base-airbnb)
278 | - Rewrite the lib to TS and add flow support
279 | - Remove lodash and use own built-in solution for debouncing
280 |
281 | ### Troubleshooting
282 |
283 | - You have included the Google Maps JavaScript API multiple times on this page. [Solution](https://github.com/ErrorPro/react-google-autocomplete/issues/89#issuecomment-846583668)
284 |
285 | ## Contribution
286 |
287 | If you would like to see something in this library please create an issue and I will implement it as soon as possible.
288 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | These versions are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | >=2.1.x | :white_check_mark: |
11 |
12 | ## Reporting a Vulnerability
13 |
14 | Open an issue or a PR with your questions/suggestion.
15 |
--------------------------------------------------------------------------------
/docs/debounce.js:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { Input, List } from "antd";
3 |
4 | import useGoogle from "react-google-autocomplete/lib/usePlacesAutocompleteService";
5 |
6 | export const Debounce = ({ a }) => {
7 | const {
8 | placePredictions,
9 | getPlacePredictions,
10 | isPlacePredictionsLoading,
11 | } = useGoogle({
12 | apiKey: process.env.REACT_APP_GOOGLE,
13 | });
14 | const [value, setValue] = useState("");
15 |
16 | return (
17 |