react-places-autocomplete
react-places-autocomplete copied to clipboard
Use placeId not id to derive the key
What is the current behavior?
The getSuggestionItemProps
function derives the key
prop based from the value of suggestion.id
, but id
is not part of the officially documented specification for the AutocompleteService. And so there are indeed some addresses where the id
is not present. However, place_id
is always present.
https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompletePrediction
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
Use this component and try to perform an address completion and render a Select component from say antd. Spread the properties returned from calling getSuggestionItemProps
into your Select.Option
element. See below for a pseudo code example.
<PlacesAutocomplete ...>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => {
const { onChange, value } = getInputProps()
return (
<Select ...>
{suggestions.map(suggestion => (
<Select.Option {...getSuggestionItemProps(suggestion)}>
{suggestion.description}
</Select.Option>
))}
</Select>
)
}}
</PlacesAutocomplete>
What is the expected behavior?
The derived key
prop should be derived from suggestion.placeId
so it's guaranteed to have a value.
Which versions of ReactPlacesAutocomplete, and which browser / OS are affected by this issue? Latest version 7.2.1
This will also be a problem any time you use suggestions.map(...)
since React needs a valid key
.
Related: https://github.com/hibiken/react-places-autocomplete/issues/276
<AutoCompleteSuggestion
{...getSuggestionItemProps(suggestion)}
key={suggestion.placeId}
>
is what we do
The workaround from @tomasswood works, just be sure that you add key={suggestion.placeId}
after the call to getSuggestionItemProps()
or you'll over write the key
with the id
instead of the desired placeId
.
Still only a workaround though, shouldn't be considered a fix for the issue.
Getting this error for children divs. My code is below showing my use of placeId as the key. No matter what I change the key to is errors.
I imagine it should not error
"react-places-autocomplete": "^7.3.0", "react": "^16.12.0",
{suggestions.map((suggestion) => {
const style = suggestion.active
? { backgroundColor: "#fafafa", cursor: "pointer" }
: { backgroundColor: "#ffffff", cursor: "pointer" };
return (
<div
{...getSuggestionItemProps(suggestion, {
className: `${
suggestion.active
? "suggestion-item--active"
: "suggestion-item"
}`,
style
})}
key={suggestion.placeId}
>
<span>{suggestion.description}</span>
</div>
);
})}