npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

google-places-autocomplete-react

v1.0.18

Published

A lightweight React component for Google Places autocomplete.

Downloads

232

Readme

Google Places Autocomplete for React

NPM Version License Downloads Bundle Size

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:

npm install google-places-autocomplete-react
yarn add google-places-autocomplete-react
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

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:

const handlePlaceSelect = (place) => {
    console.log("Place Name:", place.description);
    console.log("Latitude:", place.lat);
    console.log("Longitude:", place.lng);
};

3️⃣ Customizing Placeholder Text

<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:

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:

<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

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.
  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:

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:

// .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:

// 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:

npm install google-places-autocomplete-react@latest

3️⃣ API Quota Exceeded

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.");
        }
    }
};

4️⃣ Network Issues

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);
    }
};

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 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:

📊 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 for a detailed list of changes in each version.


⭐ If this package helped you, please consider giving it a star on GitHub!

Happy coding! 🚀