google-places-autocomplete-react
Version:
A lightweight React component for Google Places autocomplete.
449 lines (351 loc) • 13.8 kB
Markdown
# Google Places Autocomplete for React
[](https://www.npmjs.com/package/google-places-autocomplete-react)
[](https://github.com/itsahmadnyc/google-places-autocomplete-react/blob/main/LICENSE)
[](https://www.npmjs.com/package/google-places-autocomplete-react)
[](https://bundlephobia.com/package/google-places-autocomplete-react)
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.
## 🚀 Features
- ✅ **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.
## 📦 Installation
Install the package using **npm**, **yarn**, or **pnpm**:
```sh
npm install google-places-autocomplete-react
```
```sh
yarn add google-places-autocomplete-react
```
```sh
pnpm add google-places-autocomplete-react
```
### Requirements
- React 18.0.0 or higher
- A valid Google Maps API key with Places API enabled
## 📖 How to Use
### 1️⃣ Basic Usage
```jsx
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;
```
### 2️⃣ Fetching Place Details
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:**
```jsx
const handlePlaceSelect = (place) => {
console.log("Place Name:", place.description);
console.log("Latitude:", place.lat);
console.log("Longitude:", place.lng);
};
```
### 3️⃣ Customizing Placeholder Text
```jsx
<GooglePlacesAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
onPlaceSelect={handlePlaceSelect}
placeholder="Enter a city or address"
/>
```
### 4️⃣ TypeScript Usage
This package includes full TypeScript support with type definitions:
```tsx
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>
);
};
```
### 5️⃣ Styling and Customization
This component allows full customization via props and CSS:
```jsx
<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"
}}
/>
```
### 6️⃣ Advanced Example with Error Handling
```jsx
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;
```
## ⚙️ Props
| 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. |
## 🌎 Google API Setup
To use this package, you need a Google API key with the Places API enabled.
### Steps to Get an API Key:
1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Create a new project or select an existing one.
3. Enable the **Places API** under "APIs & Services".
4. Generate an API key under "Credentials".
5. Restrict the key for security (optional).
6. Use the key in the `apiKey` prop.
## 🚀 Performance Optimization
### Debouncing API Calls
For better performance and to avoid hitting API limits, consider debouncing the input:
```jsx
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}
/>
);
};
```
### Environment Variables
Always use environment variables for API keys:
```jsx
// .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}
/>
```
### Memory Management
The component automatically manages the Google Maps script loading and prevents duplicate script tags.
## 🛠 Troubleshooting & Error Handling
### Common Issues and Solutions
#### 1️⃣ Autocomplete not working?
**Possible causes:**
- Places API not enabled
- Invalid API key
- CORS issues
- Billing not set up
**Solutions:**
```jsx
// 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);
}, []);
```
#### 2️⃣ TypeScript Errors
If you're getting TypeScript errors, make sure you have the latest version:
```bash
npm install google-places-autocomplete-react@latest
```
#### 3️⃣ API Quota Exceeded
**Monitor your usage:**
```jsx
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.");
}
}
};
```
#### 4️⃣ Network Issues
**Add network error handling:**
```jsx
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);
}
};
```
#### 5️⃣ Console Warnings
**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 |
### Best Practices
1. **Always validate the API key** before deploying to production
2. **Set up proper error boundaries** in your React app
3. **Monitor API usage** to avoid unexpected charges
4. **Use environment variables** for sensitive data
5. **Implement loading states** for better UX
## 📜 License
This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details.
## 🙌 Contributing
Contributions are welcome! If you’d like to improve this package:
1. Fork the repository.
2. Create a feature branch: `git checkout -b feature-name`.
3. Commit your changes: `git commit -m "Added feature XYZ"`.
4. Push to the branch: `git push origin feature-name`.
5. Open a Pull Request.
## 💬 Support
If you encounter any issues or have suggestions, feel free to:
- 🐛 [Report a bug](https://github.com/itsahmadnyc/google-places-autocomplete-react/issues/new?labels=bug&template=bug_report.md)
- 💡 [Request a feature](https://github.com/itsahmadnyc/google-places-autocomplete-react/issues/new?labels=enhancement&template=feature_request.md)
- 💬 [Start a discussion](https://github.com/itsahmadnyc/google-places-autocomplete-react/discussions)
## 📊 Package Stats
- **Bundle size**: ~15KB minified + gzipped
- **Dependencies**: Only `react` and `prop-types`
- **Browser support**: All modern browsers (ES6+)
- **React versions**: 18.0.0+
## 🔄 Changelog
See [CHANGELOG.md](https://github.com/itsahmadnyc/google-places-autocomplete-react/blob/main/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! 🚀