Skip to content

Commit 7652acc

Browse files
authored
Merge pull request #94 from ErrorPro/v3
Rework the lib to use hooks, adding additional props and refs, bump 2…
2 parents 1a73a83 + 4597289 commit 7652acc

File tree

6 files changed

+469
-393
lines changed

6 files changed

+469
-393
lines changed

README.md

Lines changed: 88 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
![](https://img.badgesize.io/ErrorPro/react-google-autocomplete/master/lib/index.js?compression=gzip&label=gzip)
2+
![](https://img.badgesize.io/ErrorPro/react-google-autocomplete/master/lib/index.js?compression=brotli&label=brotli)
3+
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://GitHub.com/ErrorPro/react-google-autocomplete/master/LICENSE)
4+
15
## React google autocomplete
26

37
This is a simple react component for working with google [autocomplete](https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete)
@@ -13,11 +17,11 @@ As of version 1.2.4, you can now pass an `apiKey` prop to automatically load the
1317
```js
1418
<AutoComplete
1519
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
16-
onPlaceSelected={() => "do something on select"}
20+
onPlaceSelected={(place) => console.log(place)}
1721
/>
1822
```
1923

20-
Alternatively if not passing the `apiKey` prop, you can include google autocomplete link api in your app. Somewhere in index.html or somewhere else.
24+
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)
2125

2226
```html
2327
<script
@@ -26,41 +30,111 @@ Alternatively if not passing the `apiKey` prop, you can include google autocompl
2630
></script>
2731
```
2832

29-
## Example
33+
## Props
34+
35+
- `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)
36+
37+
- `ref`: [React ref](https://reactjs.org/docs/hooks-reference.html#useref) to be assigned the underlying text input ref.
38+
39+
- `autocompleteRef`: [React ref](https://reactjs.org/docs/hooks-reference.html#useref) to be assigned the [google autocomplete instance](https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete).
40+
41+
- `onPlaceSelected: (place: `[PlaceResult](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlaceResult)`, inputRef, autocompleteRef) => void`: The function gets invoked every time a user chooses location.
42+
43+
- `options`: [Google autocomplete options.](https://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions)
44+
45+
- `options.types`: By default it uses (cities).
46+
- `options.fields`: By default it uses `address_components`, `geometry.location`, `place_id`, `formatted_address`.
47+
48+
- `inputAutocompleteValue`: Autocomplete value to be set to the underlying input.
49+
50+
- `googleMapsScriptBaseUrl`: Provide custom google maps url. By default `https://maps.googleapis.com/maps/api/js`
51+
52+
- `defaultValue` prop is used for setting up the default value e.g `defaultValue={'Amsterdam'}`.
53+
54+
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.
55+
56+
## Examples
57+
58+
### Simple autocomplete with options
3059

3160
```js
3261
import Autocomplete from "react-google-autocomplete";
3362

3463
<Autocomplete
64+
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
3565
style={{ width: "90%" }}
3666
onPlaceSelected={(place) => {
3767
console.log(place);
3868
}}
39-
types={["(regions)"]}
40-
componentRestrictions={{ country: "ru" }}
69+
options={{
70+
types: ["(regions)"],
71+
componentRestrictions: { country: "ru" },
72+
}}
73+
defaultValue="Amsterdam"
4174
/>;
4275
```
4376

44-
## Typescript
77+
### Passing refs
4578

46-
We are planning on adding a full support for TS and Flow in the later releases.
79+
```js
80+
import Autocomplete from "react-google-autocomplete";
81+
82+
const inputRef = useRef(null);
83+
84+
useEffect(() => {
85+
// focus on mount
86+
inputRef.current.focus()
87+
}, [])
88+
89+
<Autocomplete
90+
ref={inputRef}
91+
onPlaceSelected={(place) => {
92+
console.log(place);
93+
}}
94+
/>;
95+
96+
```
97+
98+
### Getting access to the google autocomplete instance
4799

48100
```js
101+
import Autocomplete from "react-google-autocomplete";
102+
103+
const autocompleteRef = useRef(null);
104+
105+
<Autocomplete
106+
autocompleteRef={autocompleteRef}
107+
onPlaceSelected={(place, inputRef, theSameAutocompletRef) => {
108+
console.log(place);
109+
}}
110+
/>;
111+
112+
<button onClick={() => autocompleteRef.current.getPlace()}>Read place</button>;
113+
```
114+
115+
### Typescript
116+
117+
We are planning on adding full support for TS and Flow in the later releases.
118+
119+
```ts
49120
import Autocomplete, {
50121
ReactGoogleAutocomplete,
51122
} from "react-google-autocomplete";
52123

53124
const AutocompleteTS: FC<ReactGoogleAutocomplete> = Autocomplete as FC<ReactGoogleAutocomplete>;
54125

55-
<AutocompleteTS key="123" />
126+
<AutocompleteTS apiKey="123" />;
56127
```
57128

58-
The component has one function called `onPlaceSelected`. The function gets invoked every time a user chooses location.
59-
A `types` props means type of places in [google place API](https://developers.google.com/places/web-service/autocomplete#place_types). By default it uses (cities).
60-
A [componentRestrictions](https://developers.google.com/maps/documentation/javascript/reference#ComponentRestrictions) prop by default is empty.
61-
A [bounds](https://developers.google.com/maps/documentation/javascript/reference#AutocompleteOptions) prop by default is empty.
62-
You also can pass any props you want to the final input. You can also set [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.
63-
The `options`(optional) prop is the optional configuration to your Autocomplete instance. You can see full options [here](https://developers.google.com/maps/documentation/javascript/places-autocomplete#add_autocomplete)
129+
### More examples(dynamic props, MaterialUI) how to use the lib could be found in `examples/index.js`
130+
131+
[Video of the example](https://api.monosnap.com/file/download?id=vIjRwTxVyMj0Sd2Gjhsfie2SPk1y4l)
132+
133+
### TODO
134+
135+
- Check that it fully works with SSR
136+
- Add eslint config(base-airbnb)
137+
- Rewrite the lib to TS and add flow support
64138

65139
## Contribution
66140

examples/index.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import React, { FC, useRef, useState } from "react";
2+
import logo from "./logo.svg";
3+
import "./App.css";
4+
import { Input } from "@material-ui/core";
5+
6+
import ReactGoogleAutocompleteComponent from "../index";
7+
8+
function App() {
9+
const inputRef = useRef(null);
10+
const autocompleteRef = useRef(null);
11+
const [country, setCountry] = useState("us");
12+
13+
return (
14+
<div className="App">
15+
<header className="App-header">
16+
<ReactGoogleAutocompleteComponent
17+
ref={inputRef}
18+
placeholder="Placeholder"
19+
autocompleteRef={autocompleteRef}
20+
apiKey={process.env.GOOGLE_API_KEY}
21+
onPlaceSelected={(selected) => console.log(selected)}
22+
inputAutocompleteValue="country"
23+
/>
24+
<ReactGoogleAutocompleteComponent
25+
apiKey={process.env.GOOGLE_API_KEY}
26+
onPlaceSelected={(selected) => console.log(selected)}
27+
options={{
28+
types: ["(regions)"],
29+
componentRestrictions: { country },
30+
}}
31+
/>
32+
<ReactGoogleAutocompleteComponent
33+
apiKey={process.env.GOOGLE_API_KEY}
34+
onPlaceSelected={(selected) => console.log(selected)}
35+
/>
36+
<select
37+
onChange={(v) => {
38+
setCountry(v.target.value);
39+
}}
40+
>
41+
<option key="1" value="us">
42+
Us
43+
</option>
44+
<option key="2" value="ru">
45+
Ru
46+
</option>
47+
</select>
48+
<Input
49+
color="secondary"
50+
inputComponent={({ inputRef, onFocus, onBlur, ...props }) => (
51+
<ReactGoogleAutocompleteComponent
52+
apiKey={process.env.GOOGLE_API_KEY}
53+
onPlaceSelected={(selected) => console.log(selected)}
54+
{...props}
55+
/>
56+
)}
57+
/>
58+
<img src={logo} className="App-logo" alt="logo" />
59+
<button onClick={() => console.log(autocompleteRef)}>Press me</button>
60+
<p>
61+
Edit <code>src/App.tsx</code> and save to reload.
62+
</p>
63+
<a
64+
className="App-link"
65+
href="https://reactjs.org"
66+
target="_blank"
67+
rel="noopener noreferrer"
68+
>
69+
Learn React
70+
</a>
71+
</header>
72+
</div>
73+
);
74+
}
75+
76+
export default App;

index.d.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { HTMLProps } from "react";
2+
13
export type OptionType = {
24
componentRestrictions?: {};
35
bounds?: {};
@@ -9,17 +11,17 @@ export type OptionType = {
911
types?: string[];
1012
};
1113

12-
export interface ReactGoogleAutocomplete {
14+
export interface ReactGoogleAutocomplete<
15+
T = { current: null },
16+
B = { current: null }
17+
> extends HTMLProps<HTMLInputElement> {
1318
onPlaceSelected?: (
1419
places: Record<string, unknown>,
1520
ref: HTMLInputElement
1621
) => void;
17-
types?: string[];
18-
componentRestrictions?: {};
19-
bounds?: {};
20-
fields?: string[];
2122
inputAutocompleteValue?: string;
2223
options?: OptionType;
2324
apiKey?: string;
24-
style?: CSSStyleDeclaration;
25+
ref?: T;
26+
autocompleteRef?: B;
2527
}

0 commit comments

Comments
 (0)