Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-places-autocomplete

Package Overview
Dependencies
Maintainers
1
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-places-autocomplete

A React component for Google Maps Places Autocomplete

  • 7.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
107K
decreased by-13.92%
Maintainers
1
Weekly downloads
 
Created

What is react-places-autocomplete?

The react-places-autocomplete package is a React component that provides an easy way to integrate Google Places Autocomplete functionality into your React applications. It allows users to search for places and addresses with autocomplete suggestions powered by the Google Places API.

What are react-places-autocomplete's main functionalities?

Basic Autocomplete

This feature allows users to input a location and get autocomplete suggestions. When a suggestion is selected, it fetches the geocode and latitude/longitude of the selected place.

import React, { useState } from 'react';
import PlacesAutocomplete, { geocodeByAddress, getLatLng } from 'react-places-autocomplete';

function LocationSearchInput() {
  const [address, setAddress] = useState('');
  const [coordinates, setCoordinates] = useState({ lat: null, lng: null });

  const handleSelect = async value => {
    const results = await geocodeByAddress(value);
    const latLng = await getLatLng(results[0]);
    setAddress(value);
    setCoordinates(latLng);
  };

  return (
    <PlacesAutocomplete
      value={address}
      onChange={setAddress}
      onSelect={handleSelect}
    >
      {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
        <div>
          <input {...getInputProps({ placeholder: 'Search Places ...' })} />
          <div>
            {loading && <div>Loading...</div>}
            {suggestions.map(suggestion => {
              const style = suggestion.active
                ? { backgroundColor: '#a8dadc', cursor: 'pointer' }
                : { backgroundColor: '#ffffff', cursor: 'pointer' };
              return (
                <div {...getSuggestionItemProps(suggestion, { style })}>
                  {suggestion.description}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </PlacesAutocomplete>
  );
}

export default LocationSearchInput;

Custom Render Suggestions

This feature allows for custom rendering of autocomplete suggestions. You can style the suggestions and add custom classes based on whether they are active or not.

import React, { useState } from 'react';
import PlacesAutocomplete from 'react-places-autocomplete';

function CustomRenderSuggestions() {
  const [address, setAddress] = useState('');

  return (
    <PlacesAutocomplete
      value={address}
      onChange={setAddress}
    >
      {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
        <div>
          <input {...getInputProps({ placeholder: 'Search Places ...' })} />
          <div>
            {loading && <div>Loading...</div>}
            {suggestions.map(suggestion => {
              const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item';
              const style = suggestion.active
                ? { backgroundColor: '#fafafa', cursor: 'pointer' }
                : { backgroundColor: '#ffffff', cursor: 'pointer' };
              return (
                <div {...getSuggestionItemProps(suggestion, { className, style })}>
                  <span>{suggestion.description}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </PlacesAutocomplete>
  );
}

export default CustomRenderSuggestions;

Handling Errors

This feature demonstrates how to handle errors that may occur when fetching autocomplete suggestions from the Google Places API. It logs the error and displays an error message to the user.

import React, { useState } from 'react';
import PlacesAutocomplete from 'react-places-autocomplete';

function HandleErrors() {
  const [address, setAddress] = useState('');
  const [error, setError] = useState(null);

  const handleChange = address => {
    setAddress(address);
    setError(null);
  };

  const handleError = (status, clearSuggestions) => {
    console.log('Error from Google Maps API', status);
    setError(status);
    clearSuggestions();
  };

  return (
    <PlacesAutocomplete
      value={address}
      onChange={handleChange}
      onError={handleError}
    >
      {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
        <div>
          <input {...getInputProps({ placeholder: 'Search Places ...' })} />
          <div>
            {loading && <div>Loading...</div>}
            {suggestions.map(suggestion => {
              const style = suggestion.active
                ? { backgroundColor: '#a8dadc', cursor: 'pointer' }
                : { backgroundColor: '#ffffff', cursor: 'pointer' };
              return (
                <div {...getSuggestionItemProps(suggestion, { style })}>
                  {suggestion.description}
                </div>
              );
            })}
          </div>
          {error && <div className="error">Error: {error}</div>}
        </div>
      )}
    </PlacesAutocomplete>
  );
}

export default HandleErrors;

Other packages similar to react-places-autocomplete

Keywords

FAQs

Package last updated on 14 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc