Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
react-google-autocomplete
Advanced tools
The react-google-autocomplete package is a React component that provides an easy way to integrate Google Places Autocomplete into your React applications. It allows users to search for and select location-based suggestions, which can be used for various purposes such as filling out address forms, location-based searches, and more.
Basic Autocomplete
This feature allows you to integrate a basic Google Places Autocomplete input field into your React application. When a user selects a place, the place details are logged to the console.
import React from 'react';
import ReactGoogleAutocomplete from 'react-google-autocomplete';
function App() {
return (
<div>
<h1>Google Autocomplete Example</h1>
<ReactGoogleAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
onPlaceSelected={(place) => {
console.log(place);
}}
/>
</div>
);
}
export default App;
Restricting Search to Specific Types
This feature allows you to restrict the autocomplete suggestions to specific types, such as regions. This can be useful if you want to limit the search to certain categories of places.
import React from 'react';
import ReactGoogleAutocomplete from 'react-google-autocomplete';
function App() {
return (
<div>
<h1>Google Autocomplete with Type Restriction</h1>
<ReactGoogleAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
types={['(regions)']}
onPlaceSelected={(place) => {
console.log(place);
}}
/>
</div>
);
}
export default App;
Restricting Search to Specific Countries
This feature allows you to restrict the autocomplete suggestions to a specific country. This can be useful if your application is targeted towards users in a particular country.
import React from 'react';
import ReactGoogleAutocomplete from 'react-google-autocomplete';
function App() {
return (
<div>
<h1>Google Autocomplete with Country Restriction</h1>
<ReactGoogleAutocomplete
apiKey="YOUR_GOOGLE_API_KEY"
componentRestrictions={{ country: 'us' }}
onPlaceSelected={(place) => {
console.log(place);
}}
/>
</div>
);
}
export default App;
The react-places-autocomplete package is another React component for integrating Google Places Autocomplete into your application. It offers similar functionality to react-google-autocomplete, including the ability to restrict search results by types and countries. However, it provides more customization options for rendering the autocomplete suggestions.
The react-geosuggest package is a React component for Google Maps Places Autocomplete. It provides similar functionality to react-google-autocomplete but also includes additional features such as custom styling and event handling. It is a good alternative if you need more control over the appearance and behavior of the autocomplete component.
ReactGoogleAutocomplete
does but it does not create any dom elements. Instead, it gives you back a react ref which you can set to any input you want.debounce
prop which will reduce the amount of requests users send to Google.If you find this package helpful please give it a star because it hepls it grow and motivates us to build new features and support the old ones.
npm i react-google-autocomplete --save
or
yarn add react-google-autocomplete
As of version 1.2.4, you can now pass an apiKey
prop to automatically load the Google maps scripts. The api key can be found in your google cloud console.
<AutoComplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place) => console.log(place)}
/>
or
const { ref } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => console.log(place)
})
<AnyInput ref={ref} />
Alternatively if not passing the apiKey
prop, you can include google autocomplete link api in your app. Somewhere in index.html or somewhere else. More info here
<script
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"
></script>
This is a simple react component for working with google autocomplete
import Autocomplete from "react-google-autocomplete";
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
onPlaceSelected={(place) => {
console.log(place);
}}
/>;
apiKey
: pass to automatically load the Google maps scripts. The api key can be found in your google cloud console.
ref
: React ref to be assigned the underlying text input ref.
onPlaceSelected: (place:
PlaceResult, inputRef,
autocompleteRef) => void
: The function gets invoked every time a user chooses location.
options
: Google autocomplete options.
options.types
: By default it uses (cities).options.fields
: By default it uses address_components
, geometry.location
, place_id
, formatted_address
.inputAutocompleteValue
: Autocomplete value to be set to the underlying input.
googleMapsScriptBaseUrl
: Provide custom google maps url. By default https://maps.googleapis.com/maps/api/js
defaultValue
prop is used for setting up the default value e.g defaultValue={'Amsterdam'}
.
language
: Set language to be used for the results. If not specified, Google defaults to load the most appropriate language based on the users location or browser setting.
You can pass any prop specified for the hmtl input tag. You can also set options.fields prop if you need extra information, now it defaults to basic data in order to control expenses.
Is a hook that has a single config argument. It has exactly the same interface as ReactGoogleAutocomplete props. This hook is actually used in the ReactGoogleAutocomplete component.
import { usePlacesWidget } from "react-google-autocomplete";
export default () => {
const { ref, autocompleteRef } = usePlacesWidget({
apiKey:YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
}
});
return <AnyInput ref={ref} {...anyOtherProp}>
}
It has only one config argument which has propperties: apiKey
, ref
, onPlaceSelected
, options
, inputAutocompleteValue
, googleMapsScriptBaseUrl
. The same props described here
This hook returns object with only two properties:
ref
- is a react ref which you can assign to any input you would like.autocompleteRef
- is the autocomplete instance
This is an initial implementation of debounced google places autocomplete service. It gives you an option to reduce the amount of requests sent to google which reduce your costs. For the time being we decided to use lodash.debounce
to save time and in the later versions we might write our own implementation of debounce with hooks. Because it uses lodash we also decided to not put it into the index library file so it lives in its own file and could be only imported by it.
import usePlacesService from "react-google-autocomplete/lib/usePlacesAutocompleteService";
export default () => {
const {
placesService,
placePredictions,
getPlacePredictions,
isPlacePredictionsLoading,
} = usePlacesService({
apiKey: process.env.REACT_APP_GOOGLE,
});
useEffect(() => {
// fetch place details for the first element in placePredictions array
if (placePredictions.length)
service.placesService?.getDetails(
{
placeId: placePredictions[0].place_id,
},
(placeDetails) => savePlaceDetailsToState(placeDetails)
);
}, [placePredictions]);
return (
<>
<Input
placeholder="Debounce 500 ms"
onChange={(evt) => {
getPlacePredictions({ input: evt.target.value });
}}
loading={isPlacePredictionsLoading}
/>
{placePredictions.map((item) => renderItem(item))}
</>
);
};
The hook has only one config argument.
config
:
apiKey
: Google api key, otherwise google api has to be loaded manually.googleMapsScriptBaseUrl
: Provide custom google maps url. By default https://maps.googleapis.com/maps/api/js
.debounce
: Number of milliseconds to accumulate responses for.options
: Default options which will be passed to every request.sessionToken
: If true then a session token will be attached to every request.language
: If the language code is set, the results will be returned in the specificed languageThe hook returns an object with properties:
placesAutocompleteService
: Instance of AutocompleteServiceplacesService
: Instance of PlacesServiceautocompleteSessionToken
: Instance of AutocompleteSessionToken. You can use this to group several requests into a single sessionplacePredictions
: an array of AutocompletePredictionisPlacePredictionsLoading
: sets to true when a getPlacePredictions
request is being sent and not yet resolved.getPlacePredictions: (opt:
Options): void
: a function which you call whenever you want to request places predictions. Takes one argument.queryPredictions
: an array of QueryAutocompletePredictionisQueryPredictionsLoading
: sets to true when getQueryPredictions
request is being sent and not yet resolved.getQueryPredictions: (opt:
Options): void
: a function which you call whenever you want to request query predictions. Takes one argument.import Autocomplete from "react-google-autocomplete";
<Autocomplete
apiKey={YOUR_GOOGLE_MAPS_API_KEY}
style={{ width: "90%" }}
onPlaceSelected={(place) => {
console.log(place);
}}
options={{
types: ["(regions)"],
componentRestrictions: { country: "ru" },
}}
defaultValue="Amsterdam"
/>;
or
import { usePlacesWidget } from "react-google-autocomplete";
export default () => {
const { ref } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
options: {
types: ["(regions)"],
componentRestrictions: { country: "ru" },
},
});
return <input ref={ref} style={{ width: "90%" }} defaultValue="Amsterdam" />;
};
<Autocomplete
onPlaceSelected={(place, inputRef, autocomplete) => {
console.log(autocomplete);
}}
/>
or
const { ref, autocompleteRef } = usePlacesWidget({
apiKey: YOUR_GOOGLE_MAPS_API_KEY,
onPlaceSelected: (place) => {
console.log(place);
},
});
Formik example lives here
Debounce example lives here
We are planning on rewriting the library with TS/Flow in the later releases but you can already use it with TypeScript because we use declaration files.
If you would like to see something in this library please create an issue and I will implement it as soon as possible.
FAQs
React component for google autocomplete.
The npm package react-google-autocomplete receives a total of 127,763 weekly downloads. As such, react-google-autocomplete popularity was classified as popular.
We found that react-google-autocomplete demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.