Created
August 7, 2022 20:53
-
-
Save jeremy-code/f1f9b17fa41192353d3b58fecc4eb3eb to your computer and use it in GitHub Desktop.
React Google Autocomplete Input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback, useEffect, useRef } from "react"; | |
import useScript from "../hooks/useScript"; | |
const AutocompleteInput = () => { | |
// Load the Google Maps API script asynchronously | |
const status = useScript( | |
`https://maps.googleapis.com/maps/api/js?key=${ | |
import.meta.env.VITE_GOOGLE_MAPS_API_KEY | |
}&libraries=places` | |
); | |
const inputRef = useRef<HTMLInputElement>(null); | |
// Create a ref to hold the Google Maps autocomplete object | |
const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null); | |
// Create an instance of the autocomplete object and store it in ref | |
const createNewAutocomplete = useCallback( | |
(inputRef: React.RefObject<HTMLInputElement>) => { | |
if (!inputRef.current) return; | |
const autocomplete = new google.maps.places.Autocomplete( | |
inputRef.current, | |
{ | |
types: ["(cities)"], | |
componentRestrictions: { country: "us" }, | |
} | |
); | |
autocomplete.setFields(["geometry", "formatted_address"]); | |
autocompleteRef.current = autocomplete; | |
}, | |
[] | |
); | |
// Whenever the status changes and the status of the script is set to ready, | |
// create a new autocomplete object | |
useEffect(() => { | |
status === "ready" && createNewAutocomplete(inputRef); | |
}, [status]); | |
return <input ref={inputRef} />; | |
}; | |
export default AutocompleteInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment