### Formik Integration Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt This example shows how to integrate React Google Autocomplete with Formik, using both the component and hook approaches to manage form state for address inputs. ```APIDOC ## Formik Integration ### Description This example demonstrates integrating `react-google-autocomplete` with Formik. It showcases how to use both the `Autocomplete` component and the `usePlacesWidget` hook to manage address inputs within a Formik-controlled form. ### Method N/A (Client-side React Component) ### Endpoint N/A (Client-side React Component) ### Parameters N/A (Client-side React Component) ### Request Example ```jsx import { useFormik } from "formik"; import { TextField } from "@material-ui/core"; import Autocomplete, { usePlacesWidget } from "react-google-autocomplete"; function FormikLocationForm() { const formik = useFormik({ initialValues: { shippingAddress: "", billingAddress: "", }, onSubmit: (values) => { console.log("Form submitted:", values); alert(JSON.stringify(values, null, 2)); }, }); // Using hook with Material-UI TextField const { ref: shippingRef } = usePlacesWidget({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", onPlaceSelected: (place) => { formik.setFieldValue("shippingAddress", place.formatted_address); }, }); return (
formik.setFieldValue("billingAddress", place.formatted_address) } style={{ width: "100%", padding: "10px" }} />
Form values: {JSON.stringify(formik.values, null, 2)}
); } ``` ### Response N/A (Client-side React Component) ``` -------------------------------- ### Basic ReactGoogleAutocomplete Usage Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md A fundamental example of using the `Autocomplete` component from the 'react-google-autocomplete' library. It imports the component and renders it, allowing users to select a place. The `onPlaceSelected` prop is used to handle the selected place data. ```javascript import Autocomplete from "react-google-autocomplete"; { console.log(place); }} />; ``` -------------------------------- ### Implementing usePlacesAutocompleteService in React Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md This snippet demonstrates how to initialize the usePlacesAutocompleteService hook and handle place predictions. It includes an example of fetching place details based on user input and managing loading states. ```javascript import usePlacesService from "react-google-autocomplete/lib/usePlacesAutocompleteService"; export default () => { const { placesService, placePredictions, getPlacePredictions, isPlacePredictionsLoading, } = usePlacesService({ apiKey: process.env.REACT_APP_GOOGLE, }); useEffect(() => { if (placePredictions.length) placesService?.getDetails( { placeId: placePredictions[0].place_id, }, (placeDetails) => savePlaceDetailsToState(placeDetails) ); }, [placePredictions]); return ( <> { getPlacePredictions({ input: evt.target.value }); }} loading={isPlacePredictionsLoading} /> {placePredictions.map((item) => renderItem(item))} ); }; ``` -------------------------------- ### Initialize Autocomplete with API Key (React Hook) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Shows how to use the `usePlacesWidget` hook to get a ref for an input element, enabling Google Places Autocomplete functionality. The API key can be passed directly to the hook, which handles script loading. Requires Places API and Maps Javascript API to be enabled. ```javascript import React from 'react'; import AnyInput from './AnyInput'; // Assuming AnyInput is a custom input component import { usePlacesWidget } from 'react-google-autocomplete'; function MyComponent() { const { ref } = usePlacesWidget({ apiKey: YOUR_GOOGLE_MAPS_API_KEY, onPlaceSelected: (place) => console.log(place) }); return ; } ``` -------------------------------- ### Dynamic Options and Country Restrictions Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt This example demonstrates how to dynamically update autocomplete options, specifically by changing country restrictions based on a user's selection from a dropdown. ```APIDOC ## Dynamic Options and Country Restrictions ### Description This example illustrates how to dynamically control the `Autocomplete` component's options, focusing on updating `componentRestrictions` based on a selected country. This allows for real-time adjustments to the autocomplete behavior. ### Method N/A (Client-side React Component) ### Endpoint N/A (Client-side React Component) ### Parameters N/A (Client-side React Component) ### Request Example ```jsx import { useState, useRef } from "react"; import Autocomplete, { usePlacesWidget } from "react-google-autocomplete"; function DynamicOptionsExample() { const [country, setCountry] = useState("us"); const inputRef = useRef(null); // Component approach with dynamic options return (
{ console.log("Selected:", place.formatted_address); }} options={{ types: ["geocode", "establishment"], componentRestrictions: { country }, fields: [ "address_components", "geometry.location", "place_id", "formatted_address", "name", ], }} placeholder={`Search in ${country.toUpperCase()}`} />
); } ``` ### Response N/A (Client-side React Component) ``` -------------------------------- ### Dynamic Options and Country Restrictions with React Google Autocomplete Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt Illustrates how to dynamically update autocomplete options, specifically by changing country restrictions based on a select input. This example uses React state to manage the selected country and passes it to the Autocomplete component's options. Dependencies include React hooks (useState, useRef) and react-google-autocomplete. ```jsx import { useState, useRef } from "react"; import Autocomplete, { usePlacesWidget } from "react-google-autocomplete"; function DynamicOptionsExample() { const [country, setCountry] = useState("us"); const inputRef = useRef(null); // Component approach with dynamic options return (
{ console.log("Selected:", place.formatted_address); }} options={{ types: ["geocode", "establishment"], componentRestrictions: { country }, fields: [ "address_components", "geometry.location", "place_id", "formatted_address", "name", ], }} placeholder={`Search in ${country.toUpperCase()}`} />
); } ``` -------------------------------- ### Simple Autocomplete with Options (React) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Demonstrates a basic implementation of the Autocomplete component with custom options for place selection. It requires a Google Maps API key and uses the `onPlaceSelected` callback to handle user input. The `options` prop allows filtering results by type and country. ```javascript import Autocomplete from "react-google-autocomplete"; { console.log(place); }} options={{ types: ["(regions)"], componentRestrictions: { country: "ru" }, }} defaultValue="Amsterdam" />; ``` -------------------------------- ### Simple Autocomplete with Options (usePlacesWidget Hook) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Shows how to use the `usePlacesWidget` hook for a simpler, input-focused autocomplete implementation. This approach abstracts the underlying Google Maps API calls and provides a ref to attach to an input element. It also supports custom options and callbacks. ```javascript import { usePlacesWidget } from "react-google-autocomplete"; export default () => { const { ref } = usePlacesWidget({ apiKey: YOUR_GOOGLE_MAPS_API_KEY, onPlaceSelected: (place) => { console.log(place); }, options: { types: ["(regions)"], componentRestrictions: { country: "ru" }, }, }); return ; }; ``` -------------------------------- ### Initialize Autocomplete with API Key (React) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Demonstrates how to initialize the Autocomplete component by passing an API key directly. This method automatically loads Google Maps scripts. It requires the Places API and Maps Javascript API to be enabled in your Google Cloud Console. ```javascript import Autocomplete from "react-google-autocomplete"; console.log(place)} /> ``` -------------------------------- ### Accessing Autocomplete Instance (usePlacesWidget Hook) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Demonstrates how to access the Google Autocomplete instance when using the `usePlacesWidget` hook. The `autocompleteRef` is returned by the hook and can be used to interact with the Autocomplete service directly. ```javascript const { ref, autocompleteRef } = usePlacesWidget({ apiKey: YOUR_GOOGLE_MAPS_API_KEY, onPlaceSelected: (place) => { console.log(place); }, }); ``` -------------------------------- ### Using usePlacesWidget Hook in React Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Demonstrates how to use the `usePlacesWidget` hook to integrate Google Places Autocomplete functionality into a React component. It shows how to obtain the necessary refs and pass configuration options like API key and event handlers. ```javascript import { usePlacesWidget } from "react-google-autocomplete"; export default () => { const { ref, autocompleteRef } = usePlacesWidget({ apiKey:YOUR_GOOGLE_MAPS_API_KEY, onPlaceSelected: (place) => { console.log(place); } }); return } ``` -------------------------------- ### Accessing Autocomplete Instance (React) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Illustrates how to gain direct access to the Google Autocomplete instance when using the `Autocomplete` component. This allows for more advanced interactions with the Google Maps API. The instance is provided as the third argument to the `onPlaceSelected` callback. ```javascript { console.log(autocomplete); }} />; ``` -------------------------------- ### usePlacesWidget Hook Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Documentation for the `usePlacesWidget` hook, which provides the core logic for the autocomplete functionality and can be used independently. ```APIDOC ## usePlacesWidget Hook ### Description The `usePlacesWidget` hook encapsulates the logic for integrating Google Places Autocomplete into your React application. It has the same interface as the `ReactGoogleAutocomplete` component's props and is used internally by the component. ### Usage Import and use the hook within your functional components. ```jsx import React from 'react'; import { usePlacesWidget } from 'react-google-autocomplete'; const MyAutocompleteInput = () => { const { ref, autocompleteRef } = usePlacesWidget({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", onPlaceSelected: (place) => { console.log("Selected place:", place); }, options: { types: ["(cities)"] } }); return ( ); }; export default MyAutocompleteInput; ``` ### Arguments The hook accepts a single configuration object argument with the following properties (identical to `ReactGoogleAutocomplete` props): - `apiKey` (string) - Required - Your Google Maps API key. - `ref` (React.Ref) - Optional - A React ref to be assigned to the underlying text input element. - `onPlaceSelected` (function) - Optional - Callback for place selection. - `options` (object) - Optional - Google autocomplete options. - `inputAutocompleteValue` (string) - Optional - Programmatically set input value. - `googleMapsScriptBaseUrl` (string) - Optional - Custom URL for Google Maps scripts. - `defaultValue` (string) - Optional - Default input value. - `language` (string) - Optional - Language for results. - `libraries` (string[]) - Optional - Additional libraries to load. ### Returned Value The hook returns an object containing: - `ref` (React.Ref): A React ref that should be attached to the input element. - `autocompleteRef` (Autocomplete): The Google Autocomplete instance, providing access to its methods and properties. ### Example Response (PlaceResult) ```json { "address_components": [ { "long_name": "New York", "short_name": "NY", "types": ["state", "administrative_area_level_1", "political"] }, { "long_name": "New York", "short_name": "New York", "types": ["locality", "political"] } ], "formatted_address": "New York, NY, USA", "geometry": { "location": { "lat": 40.7127837, "lng": -74.0059413 }, "viewport": { "southwest": { "lat": 40.5774789, "lng": -74.2590871 }, "northeast": { "lat": 40.9175771, "lng": -73.7002719 } } }, "place_id": "ChIJxei_61KxwokR5f3_7W-f790", "types": ["locality", "political"] } ``` ``` -------------------------------- ### Load Google Autocomplete Script Manually (HTML) Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Provides the HTML script tag to manually load the Google Maps JavaScript API with the Places library. This is an alternative to passing the `apiKey` prop directly to the components or hooks. Ensure you replace `[YOUR_API_KEY]` with your actual Google API key. ```html ``` -------------------------------- ### Formik Integration with React Google Autocomplete Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt Demonstrates integrating React Google Autocomplete with Formik for managing form state. It shows both the component and hook approaches for handling address inputs within a controlled form. Dependencies include Formik, Material-UI (for TextField), and react-google-autocomplete. ```jsx import { useFormik } from "formik"; import { TextField } from "@material-ui/core"; import Autocomplete, { usePlacesWidget } from "react-google-autocomplete"; function FormikLocationForm() { const formik = useFormik({ initialValues: { shippingAddress: "", billingAddress: "", }, onSubmit: (values) => { console.log("Form submitted:", values); alert(JSON.stringify(values, null, 2)); }, }); // Using hook with Material-UI TextField const { ref: shippingRef } = usePlacesWidget({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", onPlaceSelected: (place) => { formik.setFieldValue("shippingAddress", place.formatted_address); }, }); return (
formik.setFieldValue("billingAddress", place.formatted_address) } style={{ width: "100%", padding: "10px" }} />
Form values: {JSON.stringify(formik.values, null, 2)}
); } ``` -------------------------------- ### Implement ReactGoogleAutocomplete Component Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt A drop-in component that renders an input field with built-in Google Places Autocomplete functionality. It triggers a callback function when a location is selected, providing access to the full Google PlaceResult object. ```jsx import Autocomplete from "react-google-autocomplete"; function LocationPicker() { const handlePlaceSelected = (place, inputRef, autocompleteRef) => { console.log("Selected place:", place.formatted_address); console.log("Place ID:", place.place_id); console.log("Coordinates:", { lat: place.geometry.location.lat(), lng: place.geometry.location.lng(), }); console.log("Address components:", place.address_components); }; return ( ); } ``` -------------------------------- ### ReactGoogleAutocomplete Component Props Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md Details the various props available for the ReactGoogleAutocomplete component, including API key, refs, event handlers, and configuration options. ```APIDOC ## ReactGoogleAutocomplete Component Props ### Description This section details the props that can be passed to the `ReactGoogleAutocomplete` component to customize its behavior and appearance. ### Props - **apiKey** (string) - Required - Your Google Maps API key. Obtain this from the [Google Cloud Console](https://developers.google.com/maps/documentation/javascript/get-api-key). - **ref** (React.Ref) - Optional - A React ref to be assigned to the underlying text input element. - **onPlaceSelected** (function) - Optional - A callback function invoked when a place is selected. It receives the `place` object, the input ref, and the autocomplete ref. - Signature: `(place: PlaceResult, inputRef: React.Ref, autocompleteRef: Autocomplete) => void` - **options** (object) - Optional - Configuration options for the Google Autocomplete service. - **options.types** (string[]) - Defaults to `['(cities)']`. Specifies the types of places to return. - **options.fields** (string[]) - Defaults to `['address_components', 'geometry.location', 'place_id', 'formatted_address']`. Specifies the fields to retrieve for each place. - **inputAutocompleteValue** (string) - Optional - The value to be programmatically set for the autocomplete input. - **googleMapsScriptBaseUrl** (string) - Optional - The base URL for loading Google Maps scripts. Defaults to `https://maps.googleapis.com/maps/api/js`. - **defaultValue** (string) - Optional - Sets the initial value of the input field (e.g., `'Amsterdam'`). - **language** (string) - Optional - The language to be used for autocomplete results. Defaults to the user's inferred or browser-set language. - **libraries** (string[]) - Optional - Additional Google Maps libraries to load alongside the Places API (e.g., `['places']`). Any standard HTML [input tag](https://www.w3schools.com/tags/tag_input.asp) props can also be passed directly. ### Example Usage ```jsx import React from 'react'; import { ReactGoogleAutocomplete } from 'react-google-autocomplete'; const MyComponent = () => { return ( { console.log(place.formatted_address); }} options={{ types: ['geocode', 'establishment'], fields: ['address_components', 'formatted_address', 'geometry.location', 'place_id'] }} defaultValue="New York" language="en" /> ); }; export default MyComponent; ``` ``` -------------------------------- ### Perform Query Predictions with usePlacesAutocompleteService (React) Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt This React hook facilitates searching for both places and general queries (e.g., 'pizza near me') using the Google Places Autocomplete Service. It offers broader search results than place-specific predictions and includes debouncing for efficient API usage. The hook returns query predictions and loading states. ```jsx import { useState } from "react"; import usePlacesAutocompleteService from "react-google-autocomplete/lib/usePlacesAutocompleteService"; function QuerySearchComponent() { const [searchValue, setSearchValue] = useState(""); const { queryPredictions, getQueryPredictions, isQueryPredictionsLoading, } = usePlacesAutocompleteService({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", debounce: 500, }); return (
{ setSearchValue(e.target.value); getQueryPredictions({ input: e.target.value }); }} /> {isQueryPredictionsLoading && Searching...}
    {queryPredictions.map((prediction, index) => (
  • {prediction.description} {prediction.place_id && (Place)}
  • ))}
); } ``` -------------------------------- ### Build Custom Address Autocomplete UI with usePlacesAutocompleteService (React) Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt This React hook provides programmatic access to Google Places Autocomplete Service, enabling custom UI development. It includes built-in debouncing to reduce API calls and supports session tokens for billing. The hook allows fetching detailed place information after a prediction is selected, offering full control over the autocomplete experience. ```jsx import { useState, useEffect } from "react"; import usePlacesAutocompleteService from "react-google-autocomplete/lib/usePlacesAutocompleteService"; function CustomAutocompleteDropdown() { const [inputValue, setInputValue] = useState(""); const [selectedPlaceDetails, setSelectedPlaceDetails] = useState(null); const { placesService, placePredictions, getPlacePredictions, isPlacePredictionsLoading, placesAutocompleteService, autocompleteSessionToken, refreshSessionToken, } = usePlacesAutocompleteService({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", debounce: 300, // Reduce API calls with 300ms debounce sessionToken: true, // Group requests into billing sessions language: "en", options: { types: ["address"], componentRestrictions: { country: "us" }, }, }); // Fetch place details when a prediction is selected const handleSelectPrediction = (prediction) => { setInputValue(prediction.description); placesService?.getDetails( { placeId: prediction.place_id, fields: ["formatted_address", "geometry", "address_components"], }, (placeDetails) => { setSelectedPlaceDetails(placeDetails); refreshSessionToken(); // Start new session after selection console.log("Full place details:", placeDetails); } ); }; return (
{ setInputValue(e.target.value); getPlacePredictions({ input: e.target.value }); }} style={{ width: "100%", padding: "10px" }} /> {isPlacePredictionsLoading &&
Loading...
} {placePredictions.length > 0 && (
    {placePredictions.map((prediction) => (
  • handleSelectPrediction(prediction)} style={{ padding: "10px", cursor: "pointer", borderBottom: "1px solid #eee" }} > {prediction.structured_formatting.main_text}
    {prediction.structured_formatting.secondary_text}
  • ))}
)} {selectedPlaceDetails && (

Selected Place Details:

{selectedPlaceDetails.formatted_address}

Lat: {selectedPlaceDetails.geometry?.location?.lat()}, Lng: {selectedPlaceDetails.geometry?.location?.lng()}

)}
); } ``` -------------------------------- ### Implement usePlacesWidget Hook Source: https://context7.com/errorpro/react-google-autocomplete/llms.txt A hook that attaches Google Places Autocomplete functionality to existing input elements, such as those from UI libraries like Material-UI or Ant Design. It returns a ref to be attached to the target input component. ```jsx import { usePlacesWidget } from "react-google-autocomplete"; import { TextField } from "@material-ui/core"; import { Input as AntInput } from "antd"; import { useRef, useState } from "react"; function CustomInputAutocomplete() { const [selectedPlace, setSelectedPlace] = useState(null); const antInputRef = useRef(null); const { ref: materialRef, autocompleteRef } = usePlacesWidget({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", onPlaceSelected: (place) => { setSelectedPlace(place); console.log("Place selected:", place.formatted_address); }, options: { types: ["geocode", "establishment"], componentRestrictions: { country: "us" }, }, language: "en", }); const { ref: antRef } = usePlacesWidget({ apiKey: "YOUR_GOOGLE_MAPS_API_KEY", onPlaceSelected: (place) => { antInputRef.current?.setValue(place?.formatted_address); }, }); return (

Material-UI TextField

Ant Design Input

{ antInputRef.current = c; if (c) antRef.current = c.input; }} size="large" placeholder="Search location..." />
); } ``` -------------------------------- ### usePlacesAutocompleteService Hook Source: https://github.com/errorpro/react-google-autocomplete/blob/master/README.md A React hook to manage Google Places autocomplete predictions with built-in debouncing. ```APIDOC ## usePlacesAutocompleteService ### Description A hook that provides a debounced interface to the Google Places Autocomplete service, reducing API call frequency. ### Method React Hook (Client-side) ### Parameters #### Config Object - **apiKey** (string) - Required - Your Google Maps API key. - **googleMapsScriptBaseUrl** (string) - Optional - Custom URL for loading the Google Maps script. Default: https://maps.googleapis.com/maps/api/js - **debounce** (number) - Optional - Milliseconds to wait before triggering a request. - **options** (object) - Optional - Default AutocompletionRequest options passed to every request. - **sessionToken** (boolean) - Optional - If true, attaches a session token to requests. - **language** (string) - Optional - Language code for the returned results. - **libraries** (array) - Optional - Additional libraries to load. Default: ["places"] ### Request Example const { placesService, placePredictions, getPlacePredictions } = usePlacesAutocompleteService({ apiKey: "YOUR_KEY", debounce: 500 }); ### Response #### Returns - **placesService** (object) - The underlying Google Places Service instance. - **placePredictions** (array) - List of autocomplete predictions. - **getPlacePredictions** (function) - Function to trigger a new prediction request. - **isPlacePredictionsLoading** (boolean) - Loading state indicator. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.