Installation
How to install and set up autocompletecn in your project.
Prerequisites
- A project with Tailwind CSS set up.
- A Google Maps API key with the Places API (New) enabled. Below there's a guide on how to get one.
Installation
Run the following command:
npx shadcn@latest add https://autocompletecn.vercel.app/r/autocomplete.jsonOr just the hook:
npx shadcn@latest add https://autocompletecn.vercel.app/r/use-autocomplete.jsonThis gives you all the useAutocomplete capabilities without any UI components.
Usage
Import and use the autocomplete component:
import { Autocomplete } from "@/components/ui/autocomplete";
export function AddressForm() {
return (
<Autocomplete
apiKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!}
placeholder="Search for an address..."
onPlaceSelect={(details) => {
console.log(details.formattedAddress);
console.log(details.city, details.postalCode);
}}
/>
);
}Check the Usage page for more examples.
Hook-only Usage
Use the hook directly to build a custom autocomplete experience:
import { useAutocomplete } from "@/hooks/use-autocomplete";
export function CustomAutocomplete() {
const {
isLoaded,
getSuggestions,
getPlaceDetails,
places,
} = useAutocomplete(process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!);
const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
getSuggestions(e.target.value, { includedPrimaryTypes: ["route"] });
};
const handleSelect = async (prediction: google.maps.places.PlacePrediction) => {
const details = await getPlaceDetails(prediction);
console.log(details);
};
return (
<div>
<input
type="text"
onChange={handleInput}
disabled={!isLoaded}
placeholder="Type an address..."
/>
<ul>
{places?.map((place) => (
<li key={place.placeId}>
<button onClick={() => handleSelect(place)}>
{place.mainText?.text}
</button>
</li>
))}
</ul>
</div>
);
}Note: The component manages Google Maps Places API session tokens automatically by default. Check the Session Token page for more details.
Google Maps API Key Guide
Follow the steps below to get a Google Maps API key with the Places API (New) enabled:
1
Activate the Places API (New)
Go to the Google Cloud Console and search for APIs & Services
Then click on "Enable APIs and Services"
In the search bar, type "Places API (New)" and click on it
Then click on "Enable"
2
Create a new API key
Back in the APIs & Services page, click on "Credentials" in the left sidebar
Then click on "Create credentials"
Select "API key", fill the required fields and click on "Create"
Once you have the API key, I recommend you to store it in a
.env file as NEXT_PUBLIC_GOOGLE_MAPS_API_KEY