React hook for Google Maps Places Autocomplete.
React hook for Google Maps Places Autocomplete.
We're actively seeking dedicated maintainers for the repo — if you're interested, please contact me directly.
This is a React hook for Google Maps Places Autocomplete, which helps you build a UI component with the feature of place autocomplete easily! By leveraging the power of Google Maps Places API, you can provide a great UX (user experience) for user interacts with your search bar or form, etc. Hope you guys it.
❤️ it? ⭐️ it on GitHub or Tweet about it.
⚡️ Try yourself: https://use-places-autocomplete.netlify.app
react.To use use-places-autocomplete, you must use [email protected] or greater which includes hooks.
This package is distributed via npm.
$ yarn add use-places-autocomplete
# or
$ npm install --save use-places-autocompleteWhen working with TypeScript you need to install the @types/google.maps as a devDependencies.
$ yarn add --dev @types/google.maps
# or
$ npm install --save-dev @types/google.mapsusePlacesAutocomplete is based on the Places Autocomplete (or more specific docs) of Google Maps Place API. If you are unfamiliar with these APIs, we recommend you review them before we start.
To use this hook, there're two things we need to do:
Use the script tag to load the library in your project and pass the value of the callback parameter to the callbackName option.
⚠️ If you got a global function not found error. Make sure
usePlaceAutocompleteis declared before the script was loaded. You can use the async or defer attribute of the `` element to achieve that.
Now we can start to build our component. Check the API out to learn more.
…react-cool-onclickoutside is my other hook library, which can help you handle the interaction of user clicks outside of the component(s).
Easy right? This is the magic of usePlacesAutocomplete ✨. I just showed you how it works via a minimal example. However, you can build a UX rich autocomplete component, like WAI-ARIA compliant and keyword interaction like my demo, by checking the code or integrating this hook with the combobox of Reach UI to achieve that.
…When loading the Google Maps Places API via a 3rd-party library, you may need to wait for the script to be ready before using this hook. However, you can lazily initialize the hook in the following ways, depending on your use case.
import usePlacesAutocomplete from "use-places-autocomplete";
const App = () => {
const { init } = usePlacesAutocomplete({
initOnMount: false, // Disable initializing when the component mounts, default is true
});
const [loading] = useGoogleMapsApi({
library: "places",
onLoad: () => init(), // Lazily initializing the hook when the script is ready
});
return
;
};import usePlacesAutocomplete from "use-places-autocomplete";
const PlacesAutocomplete = () => {
const { ready, value, suggestions, setValue } = usePlacesAutocomplete();
return
;
};
const App = () => {
const [loading] = useGoogleMapsApi({ library: "places" });
return (
);
};By default, this library caches the response data to help you save the cost of Google Maps Places API and optimize search performance.
const methods = usePlacesAutocomplete({
// Provide the cache time in seconds, the default is 24 hours
cache: 24 * 60 * 60,
});By the way, the cached data is stored via the Window.sessionStorage API.
You may need to have multiple caches. For example, if you use different place type restrictions for different pickers in your app.
const methods = usePlacesAutocomplete({
// Provide a custom cache key
cacheKey: "region-restricted",
});Note that usePlacesAutocomplete will prefix this with
upa-, so the above would becomeupa-region-restrictedin sessionStorage.
const returnObj = usePlacesAutocomplete(parameterObj);When using usePlacesAutocomplete, you can configure the following options via the parameter.
| Key | Type | Default | Description |
|---|---|---|---|
requestOptions |
object | The request options of Google Maps Places API except for input (e.g. bounds, radius, etc.). |
|
googleMaps |
object | window.google.maps |
In case you want to provide your own Google Maps object, pass the google.maps to it. |
callbackName |
string | The value of the callback parameter when loading the Google Maps JavaScript library. |
|
debounce |
number | 200 |
Number of milliseconds to delay before making a request to Google Maps Places API. |
cache |
number | false | 86400 (24 hours) |
Number of seconds to cache the response data of Google Maps Places API. |
cacheKey |
string | "upa" |
Optional cache key so one can use multiple caches if needed. |
defaultValue |
string | "" |
Default value for the input element. |
initOnMount |
boolean | true |
Initialize the hook with Google Maps Places API when the component mounts. |
It's returned with the following properties.
| Key | Type | Default | Description |
|---|---|---|---|
ready |
boolean | false |
The ready status of usePlacesAutocomplete. |
value |
string | "" |
value for the input element. |
suggestions |
object | { loading: false, status: "", data: [] } |
See suggestions. |
setValue |
function | (value, shouldFetchData = true) => {} |
See setValue. |
clearSuggestions |
function | See clearSuggestions. | |
clearCache |
function | (key = cacheKey) => {} |
Clears the cached data. |
init |
function | Useful when lazily initializing the hook. |
The search result of Google Maps Places API, which contains the following properties:
loading: boolean - indicates the status of a request is pending or has been completed. It's useful for displaying a loading indicator for the user.status: string - indicates the status of the API response, which has these values. It's useful to decide whether we should display the dropdown orNo open issues yet, or sync has not completed.