Skip to content

Instantly share code, notes, and snippets.

@jeremy-code
Created August 7, 2022 20:53
Show Gist options
  • Save jeremy-code/f1f9b17fa41192353d3b58fecc4eb3eb to your computer and use it in GitHub Desktop.
Save jeremy-code/f1f9b17fa41192353d3b58fecc4eb3eb to your computer and use it in GitHub Desktop.
React Google Autocomplete Input
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