A lightweight and easy-to-use Google Places Autocomplete component for React applications. It allows users to search for locations and fetch place details using the Google Places API.
- ✅ Google Places API Integration – Fetch place suggestions in real-time.
- ✅ Lightweight & Fast – Minimal dependencies and optimized performance.
- ✅ Customizable – Fully controllable via props.
- ✅ Easy to Integrate – Works out of the box with any React app.
- ✅ TypeScript Support – Includes TypeScript types for better development experience.
Install the package using npm, yarn, or pnpm:
npm install google-places-autocomplete-react
yarn add google-places-autocomplete-react
pnpm add google-places-autocomplete-react
- React 18.0.0 or higher
- A valid Google Maps API key with Places API enabled
import React from "react";
import GooglePlacesAutocomplete from "google-places-autocomplete-react";
const App = () => {
const handlePlaceSelect = (place) => {
console.log("Selected Place:", place);
};
return (
<div style={{ maxWidth: "400px", margin: "50px auto" }}>
<GooglePlacesAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
onPlaceSelect={handlePlaceSelect}
/>
</div>
);
};
export default App;
The onPlaceSelect
callback receives an object containing:
-
description
- The name of the selected place. -
lat
- Latitude of the location. -
lng
- Longitude of the location.
Example:
const handlePlaceSelect = (place) => {
console.log("Place Name:", place.description);
console.log("Latitude:", place.lat);
console.log("Longitude:", place.lng);
};
<GooglePlacesAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
onPlaceSelect={handlePlaceSelect}
placeholder="Enter a city or address"
/>
This package includes full TypeScript support with type definitions:
import React from "react";
import GooglePlacesAutocomplete, {
PlaceDetails,
GooglePlacesAutocompleteProps
} from "google-places-autocomplete-react";
const App: React.FC = () => {
const handlePlaceSelect = (place: PlaceDetails) => {
console.log("Selected Place:", place);
// place.description - string
// place.lat - number
// place.lng - number
};
const props: GooglePlacesAutocompleteProps = {
apiKey: "YOUR_GOOGLE_API_KEY",
onPlaceSelect: handlePlaceSelect,
placeholder: "Search for a location...",
inputClassName: "my-input"
};
return (
<div>
<GooglePlacesAutocomplete {...props} />
</div>
);
};
This component allows full customization via props and CSS:
<GooglePlacesAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
onPlaceSelect={handlePlaceSelect}
inputClassName="custom-input"
suggestionsClassName="custom-suggestions"
suggestionItemClassName="custom-suggestion-item"
inputStyle={{
padding: "12px",
fontSize: "16px",
border: "2px solid #e1e5e9",
borderRadius: "8px",
width: "100%"
}}
suggestionsStyle={{
backgroundColor: "white",
borderRadius: "8px",
boxShadow: "0 4px 6px rgba(0,0,0,0.1)",
border: "1px solid #e1e5e9"
}}
suggestionItemStyle={{
padding: "12px",
cursor: "pointer",
borderBottom: "1px solid #f0f0f0"
}}
/>
import React, { useState } from "react";
import GooglePlacesAutocomplete from "google-places-autocomplete-react";
const LocationPicker = () => {
const [selectedPlace, setSelectedPlace] = useState(null);
const [error, setError] = useState("");
const handlePlaceSelect = (place) => {
try {
setSelectedPlace(place);
setError("");
// You can now use the coordinates
console.log(`Location: ${place.description}`);
console.log(`Coordinates: ${place.lat}, ${place.lng}`);
// Example: Save to local storage
localStorage.setItem('selectedPlace', JSON.stringify(place));
} catch (err) {
setError("Failed to process selected location");
console.error(err);
}
};
return (
<div style={{ maxWidth: "500px", margin: "20px auto", padding: "20px" }}>
<h2>Select Your Location</h2>
<GooglePlacesAutocomplete
apiKey={process.env.REACT_APP_GOOGLE_API_KEY}
onPlaceSelect={handlePlaceSelect}
placeholder="Enter your address or location..."
inputStyle={{
padding: "15px",
fontSize: "16px",
border: error ? "2px solid red" : "2px solid #ddd",
borderRadius: "8px",
width: "100%",
boxSizing: "border-box"
}}
suggestionsStyle={{
backgroundColor: "white",
borderRadius: "8px",
boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
marginTop: "5px"
}}
/>
{error && (
<p style={{ color: "red", marginTop: "10px" }}>{error}</p>
)}
{selectedPlace && (
<div style={{
marginTop: "20px",
padding: "15px",
backgroundColor: "#f8f9fa",
borderRadius: "8px"
}}>
<h3>Selected Location:</h3>
<p><strong>Address:</strong> {selectedPlace.description}</p>
<p><strong>Latitude:</strong> {selectedPlace.lat}</p>
<p><strong>Longitude:</strong> {selectedPlace.lng}</p>
</div>
)}
</div>
);
};
export default LocationPicker;
Prop Name | Type | Required | Description |
---|---|---|---|
apiKey |
string |
✅ Yes | Your Google Maps API key. |
onPlaceSelect |
function |
✅ Yes | Callback function triggered when a place is selected. |
placeholder |
string |
❌ No | Placeholder text for the input field (default: "Search for a location"). |
inputClassName |
string |
❌ No | Custom class name for the input field. |
suggestionsClassName |
string |
❌ No | Custom class name for the suggestions dropdown. |
suggestionItemClassName |
string |
❌ No | Custom class name for each suggestion item. |
inputStyle |
object |
❌ No | Inline styles for the input field. |
suggestionsStyle |
object |
❌ No | Inline styles for the suggestions container. |
suggestionItemStyle |
object |
❌ No | Inline styles for suggestion items. |
To use this package, you need a Google API key with the Places API enabled.
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the Places API under "APIs & Services".
- Generate an API key under "Credentials".
- Restrict the key for security (optional).
- Use the key in the
apiKey
prop.
For better performance and to avoid hitting API limits, consider debouncing the input:
import { useMemo, useCallback } from "react";
import { debounce } from "lodash";
const OptimizedLocationPicker = () => {
// Debounce the place selection to avoid excessive API calls
const debouncedPlaceSelect = useMemo(
() => debounce((place) => {
console.log("Selected:", place);
// Your logic here
}, 300),
[]
);
return (
<GooglePlacesAutocomplete
apiKey="YOUR_API_KEY"
onPlaceSelect={debouncedPlaceSelect}
/>
);
};
Always use environment variables for API keys:
// .env file
REACT_APP_GOOGLE_API_KEY=your_actual_api_key_here
// In your component
<GooglePlacesAutocomplete
apiKey={process.env.REACT_APP_GOOGLE_API_KEY}
onPlaceSelect={handlePlaceSelect}
/>
The component automatically manages the Google Maps script loading and prevents duplicate script tags.
Possible causes:
- Places API not enabled
- Invalid API key
- CORS issues
- Billing not set up
Solutions:
// Add error handling to your component
const [apiError, setApiError] = useState("");
useEffect(() => {
// Check if Google Maps loaded successfully
const checkGoogleMaps = () => {
if (!window.google) {
setApiError("Google Maps API failed to load. Check your API key.");
}
};
setTimeout(checkGoogleMaps, 3000);
}, []);
If you're getting TypeScript errors, make sure you have the latest version:
npm install google-places-autocomplete-react@latest
Monitor your usage:
const handlePlaceSelect = (place) => {
try {
// Your place handling logic
console.log("API call successful:", place);
} catch (error) {
if (error.message.includes("OVER_QUERY_LIMIT")) {
console.error("API quota exceeded. Check your billing settings.");
}
}
};
Add network error handling:
const [isLoading, setIsLoading] = useState(false);
const [networkError, setNetworkError] = useState("");
const handlePlaceSelect = async (place) => {
setIsLoading(true);
setNetworkError("");
try {
// Process the place data
await processPlace(place);
} catch (error) {
setNetworkError("Network error. Please check your connection.");
} finally {
setIsLoading(false);
}
};
Common warnings and fixes:
Warning | Solution |
---|---|
Google Maps API loaded multiple times |
The component handles this automatically |
API key not provided |
Ensure your API key is correctly set |
Places service not available |
Check if Places API is enabled |
- Always validate the API key before deploying to production
- Set up proper error boundaries in your React app
- Monitor API usage to avoid unexpected charges
- Use environment variables for sensitive data
- Implement loading states for better UX
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! If you’d like to improve this package:
- Fork the repository.
- Create a feature branch:
git checkout -b feature-name
. - Commit your changes:
git commit -m "Added feature XYZ"
. - Push to the branch:
git push origin feature-name
. - Open a Pull Request.
If you encounter any issues or have suggestions, feel free to:
- Bundle size: ~15KB minified + gzipped
-
Dependencies: Only
react
andprop-types
- Browser support: All modern browsers (ES6+)
- React versions: 18.0.0+
See CHANGELOG.md for a detailed list of changes in each version.
⭐ If this package helped you, please consider giving it a star on GitHub!
Happy coding! 🚀